3

Java を使用しProcessBuilderて、子プロセスのグループを作成しています。waitFor()結果のオブジェクトのメソッドを使用してProcess、その特定の子が終了するのを待つことができます。

UNIXシステム コールのように、子が終了するまでブロックすることはできますか?wait()

4

3 に答える 3

10

最初のステップは、次のように、各サブプロセスによって行われた作業をFutureとして表すことです。

final ProcessBuilder builder = ...;

// for each process you're going to launch
FutureTask task = new FutureTask(new Callable<Integer>() {
  @Override public Integer call() {
    return builder.start().waitFor();
  }
};

すべてのタスクをエグゼキューターに送信します。

ExecutorService executor = Executors.newCachedThreadPool();
for (FutureTask task : tasks) {
  executor.submit(task);
}

// no more tasks are going to be submitted, this will let the executor clean up its threads
executor.shutdown();

次に、優れたExecutorCompletionServiceクラスを使用します。

ExecutorCompletionService service = new ExecutorCompletionService(executor);
while (!executor.isTerminated()) {
  Future<Integer> finishedFuture = service.take();
  System.out.println("Finishing process returned " + finishedFuture.get());
}

このループは、完了したタスクごとに 1 回反復されます。returnValue子プロセスの終了コードになります。

これで、どのプロセスが完了したか正確にはわかりません。Callable を Integer を返す代わりに変更して、プロセスを返すか、プロセスの出力を表す独自のクラスを返すことができます。

ああ、もちろん、すべてのタスクを待つ必要がない場合は、take()1 回だけ呼び出すことができます。

于 2011-01-07T07:08:13.857 に答える
0

CountDownLatchについて読む

CountDownLatch は、指定されたカウントで初期化されます。await メソッドは、countDown() メソッドの呼び出しによって現在のカウントがゼロになるまでブロックします。その後、待機中のすべてのスレッドが解放され、後続の await の呼び出しはすぐに戻ります。これは 1 回限りの現象で、カウントをリセットすることはできません。カウントをリセットするバージョンが必要な場合は、CyclicBarrier の使用を検討してください。

于 2011-01-07T05:14:49.093 に答える
-2

you have to use some form of IPC to achieve this. If you are allowed to use native libraries and if you work on UNIX/Linux platform try using the same wait() system call by writing a simple JNI wrapper & calling the native method from java code.

If you cannot use native IPC mechanisms use TCP/IP server/client mechanism in which you control the child process exit from the server while the client connects/disconnects to/from the server. When there are no child connections you can exit the server program!

于 2011-01-07T06:38:57.560 に答える