温馨提示×

java等待多线程执行完成的方法是什么

小亿
97
2023-09-15 13:06:28
栏目: 编程语言

Java中等待多线程执行完成的方法有以下几种:

  1. 使用Thread的join方法:调用线程的join方法可以等待该线程执行完成。例如,如果线程A执行了线程B的join方法,那么线程A会阻塞,直到线程B执行完成。
Thread thread1 = new Thread(() -> {
// 线程1的任务
});
Thread thread2 = new Thread(() -> {
// 线程2的任务
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 所有线程执行完成后继续执行的代码
  1. 使用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();
}
// 所有线程执行完成后继续执行的代码
  1. 使用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();
// 所有线程执行完成后继续执行的代码

这些方法可以根据具体的场景选择使用。

0