マルチスレッドの実行完了をJavaで待機する方法
Javaにおけるマルチスレッド実行を完了するまで待機する方法の選択肢は次のとおりです。
- スレッドのjoinメソッドを使用すれば、呼び出したスレッドの実行を待つことができます。例えば、スレッドAがスレッドBのjoinメソッドを実行すると、スレッドBの実行完了までスレッドAはブロックされます。
Thread thread1 = new Thread(() -> {
// 线程1的任务
});
Thread thread2 = new Thread(() -> {
// 线程2的任务
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 所有线程执行完成后继续执行的代码
- CountDownLatchクラスを活用する:CountDownLatchは、スレッド同期に役立つユーティリティクラスで、スレッドグループの実行完了を待機できます。CountDownLatchのawaitメソッドを使用して、スレッドの実行を待機します。
CountDownLatch latch = new CountDownLatch(2);
Thread thread1 = new Thread(() -> {
// 线程1的任务
latch.countDown();
});
Thread thread2 = new Thread(() -> {
// 线程2的任务
latch.countDown();
});
thread1.start();
thread2.start();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 所有线程执行完成后继续执行的代码
- ExecutorServiceとFutureを用いる:ExecutorServiceは、複数のタスクを実行できるスレッドプールで、Futureはタスクが完了した後にその結果を取得できる。Futureのgetメソッドを使用して、すべてのタスクの完了を待機できる。
ExecutorService executorService = Executors.newFixedThreadPool(2);
List<Future<?>> futures = new ArrayList<>();
futures.add(executorService.submit(() -> {
// 线程1的任务
}));
futures.add(executorService.submit(() -> {
// 线程2的任务
}));
for (Future<?> future : futures) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
executorService.shutdown();
// 所有线程执行完成后继续执行的代码
場面に応じて使い分けられる手法です。