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

41次阅读
没有评论

共计 1189 个字符,预计需要花费 3 分钟才能阅读完成。

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();
// 所有线程执行完成后继续执行的代码 

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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-20发表,共计1189字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)