これにはいくつかの方法があります。ジョンが指摘しているように、この方法でスレッドを実行しても意味がありません。他のスレッドの出力でスレッドがブロックされ、事実上並列化が達成されないからです。
私の「好ましい」解決策はExecutorService
、ピーターが述べたように use ですが、少し異なります。これが単純なアプローチの 1 つです。
ExecutorService executor = Executors.newSingleThreadExecutor();
final Future<String> output1 = executor.submit(new Callable<String>() {
@Override public String call() {
// do Something
return "a String from Task #1";
}
});
final Future<String> output2 = executor.submit(new Callable<String>() {
@Override public String call() throws Exception{
// do Something
// Wait for the output of the above task using `Future.get()`.
return output1.get() + ", a String from Task #2";
}
});
Future<String> output3 = executor.submit(new Callable<String>() {
@Override public String call() throws Exception{
// do Something
return output2.get() + ", a String from Task #3";
}
});
System.err.print("Output from 3rd task: " + output3.get());
スレッドを使用してこれを行う他の方法: 共有ブロッキング データ構造 (たとえばBlockingQueue
、結果を安全に公開するためのスレッド間)。結果が渡されず、他のスレッドへの終了のシグナルのみが必要な場合は、CountDownLatch
es.