在Java中,可以使用Thread.join()方法、ExecutorService以及CountDownLatch等方式来实现主线程等待子线程执行完毕。以下是其中的一些方法:
-
使用
Thread.join()方法: 在Java中,Thread类提供了join()方法,可以用于让主线程等待子线程执行完毕。例如:Thread myThread = new Thread(() -> { // 子线程的工作 }); // 启动子线程 myThread.start(); // 主线程等待子线程完成 try { myThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } // 主线程继续执行 -
使用
ExecutorService: 使用ExecutorService可以更方便地管理线程池,并等待所有线程执行完成。例如:ExecutorService executorService = Executors.newFixedThreadPool(5); // 提交任务给线程池 Future<?> future = executorService.submit(() -> { // 子线程的工作 }); // 主线程等待子线程完成 try { future.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } // 主线程继续执行 -
使用
CountDownLatch:CountDownLatch是一个同步辅助类,可以让一个或多个线程等待其他线程完成操作。例如:import java.util.concurrent.CountDownLatch; public class Main { public static void main(String[] args) { CountDownLatch latch = new CountDownLatch(1); Thread myThread = new Thread(() -> { // 子线程的工作 latch.countDown(); // 子线程工作完成,减少计数器 }); // 启动子线程 myThread.start(); try { // 主线程等待计数器变为0 latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } // 主线程继续执行 } }