1

Runnable オブジェクトを使用して processCommand を実行し、ある程度の時間がかかる処理を行います (内部プロセスと呼びましょう)。内部プロセスの最後に、テキスト ファイルに何かを書き込みます。これは、指定された時間内にプロセスがまだ完了していない場合、強制終了する必要があるため、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();
    }

}
4

1 に答える 1