public static void main(String[] args) throws InterruptedException { List<String> list = new ArrayList<>(); //1、 创建CountDownLatch 对象, 设定需要计数的子线程数目 final CountDownLatch latch=new CountDownLatch(3); System.out.println("主线程开始执行...."); for (int i = 0; i < 3; i++) { new Thread(){ @Override public void run() { try { System.out.println(Thread.currentThread().getName()+" 开始执行存储过程.."); list.add(Thread.currentThread().getName()); Thread.sleep(2000); System.out.println(Thread.currentThread().getName()+" 存储过程执行完毕..."); //2、子线程执行完毕,计数减1 latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); } System.out.println("等待子线程执行完毕..."); //3、 当前线程挂起等待 latch.await(); System.out.println("主线程执行完毕...."); for(String string:list){ System.out.println("执行结果: "+string); } }
java 实现多个子线程执行完毕后,再执行主线程
于 2022-05-13 15:15:30 首次发布