2

私のプログラムには n 個のテスト スクリプトのリストがあり、リストを反復して 3 つのテスト スクリプトを並行して実行する必要があります。このタスクを達成するために、サイズ 3 の Threadpool を作成しました。スレッド プールの実装は以下のようになります。

ExecutorService executor = Executors.newFixedThreadPool(3);
for (int threadpoolCount = 0; threadpoolCount < classNames.size(); threadpoolCount++) {
    Runnable worker = new ProcessRunnable(classNames.get(threadpoolCount));
    executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}

System.out.println("Finished all threads");

以下は、Mavenコマンドを含むバッチファイルを実行する私のスレッド実装です

public void run() {
    try {
        System.out.println(testname);
        System.out.println("Task ID : " + this.testname + " performed by " + Thread.currentThread().getName());
        Process p = Runtime.getRuntime().exec("cmd /C Junit_runner.bat" + " " + testname);
        p.waitFor();
        Thread.sleep(5000);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

これがコンソールに表示されるものです(コマンドプロンプトを起動してバックグラウンドで実行していません)

com.selenium.test.testname1 タスク ID : com.selenium.test.testname1 は、pool-1-thread-1 によって実行されました

com.selenium.test.testname1 タスク ID : com.selenium.test.testname2 は、pool-1-thread-2 によって実行されます

com.selenium.test.testname1 タスク ID : com.selenium.test.testname3 は、pool-1-thread-3 によって実行されます

実行はここで一時停止し、何もしませんでした。背後で何が起こっているのかわかりません。また、バッチファイルが正常に機能することをクロスチェックしました。

4

2 に答える 2

2

プロセスの実行に時間がかかるため、コントロールが戻ってきません。

public abstract int waitFor() throws InterruptedException

この Process オブジェクトによって表されるプロセスが終了するまで、必要に応じて現在のスレッドを待機させます。サブプロセスがすでに終了している場合、このメソッドはすぐに戻ります。サブプロセスがまだ終了していない場合、呼び出しスレッドはサブプロセスが終了するまでブロックされます。

ブロッキング コールと同様waitFor()に、3 つのスレッドすべてがこの行で停止します。

注:本質的にそれ自体をブロックする必要はThread.sleep(5000);ありません。waitFor()

他のコマンドを実行して、制御が戻るかどうかを確認してください。

また、代わりに:

while (!executor.isTerminated()) {
}

ExecutorService#awaitTermination()を使用できます

于 2013-08-05T07:39:59.303 に答える