簡體   English   中英

使用executorservice控制運行時過程

[英]Using executorservice to control runtime process

我使用一個Runnable對象來運行processCommand並執行一些處理,這些處理會花費一些時間(我們稱其為process內部)。 在內部流程的最后,它將向文本文件中寫入一些內容。 這個想法是,如果在指定的時間內內部進程仍未完成,則必須將其終止,因此我使用ExecutorService對其進行處理。 但是,如果內部進程早於指定時間完成,它將中斷ExecutorService,以便主線程可以繼續執行下一個任務。

但是問題是,有時,內部進程根本不創建文件,或者創建了文件,但是里面沒有任何內容。 當內部進程早於指定時間完成時,就會發生這種情況。 我不知道我的實現有什么問題。 請注意,如果我手動執行該過程(不使用ExecutorService),則該過程運行良好,並且可以正確寫入所有內容。

在這里,我發布我的代碼來完成工作:

public void process(){


    for (int i = 0; i < stoppingTime.length; i++) {
        for (int j = 2 * i; j < 2 * (i + 1); j++) {
            final int temp = j;
            ExecutorService executor = Executors.newSingleThreadExecutor();

            Runnable r = new Runnable() {

                @Override
                public void run() {
                    Process p = null;

                    int ex = 1;

                    try {
                        p = Runtime.getRuntime().exec(
                                processCommand.get(temp));

                        while (ex != 0) {
                            try {
                                //sleep every 30 second then check the exitValue
                                Thread.sleep(30000);
                            } catch (InterruptedException e) {

                            }
                            ex = p.exitValue();
                            p.destroy();                                
                        }                           
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("IOException");
                    }
                }

            };

            Future future = executor.submit(r);

            try {
                System.out.println("Started..");
                future.get(stoppingTime[i], TimeUnit.SECONDS);                  
                System.out.println("Finished!");
            } catch (TimeoutException e) {
                System.out.println("Terminated!");
            } catch (InterruptedException e) {
                System.out.println("Future gets InterruptedException");
            } catch (ExecutionException e) {
                System.out.println("Future gets ExecutionException");
            }
            executor.shutdownNow();
            System.out.println("shutdown executor");
        }
        System.out.println();
    }

}

老問題,以為我還是會嘗試的。

首先,在雙循環內,在與已定義的Runnable相同的塊中獲得ExecutorService 如果您想獲取本機執行的"processCommand"的返回值,然后繼續執行您所說的下一個任務,那么您需要在循環之前實例化該ExecutorService來重用該ExecutorService

其次, stoppingTime[i]intFuture.get(...)需要long

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM