高校网站建设需求分析报告,有没有做线播放网站,做政协网站软件的公司,营销咨询公司属于金融机构吗CountDownLatch是JUC提供的解决方案 CountDownLatch 可以保证一组子线程全部执行完牛后再进行主线程的执行操作。例如#xff0c;主线程启动前#xff0c;可能需要启动并执行若干子线程#xff0c;这时就可以通过 CountDownLatch 来进行控制。 CountDownLatch是通过一个线程…CountDownLatch是JUC提供的解决方案 CountDownLatch 可以保证一组子线程全部执行完牛后再进行主线程的执行操作。例如主线程启动前可能需要启动并执行若干子线程这时就可以通过 CountDownLatch 来进行控制。 CountDownLatch是通过一个线程个数的计数器实现的同步处理操作在初始化时可以为CountDownLatch设置一个线程执行总数这样每当一个子线程执行完毕后都要执行减1操作当所有的子线程都执行完毕后CountDownLatch中保存的计数为0则主线程恢复执行。 CountDownLatch类常用方法
方法描述public CountDownLatch(int count)定义等待子线程总数public void await() throws InterruptedException主线程阻塞等待子线程执行完毕public void countDown()子线程执行完后减少等待数量public long getCount()获取当前等待数量
实现代码
public static void main(String[] args) throws Exception {int n 3;String[] tasks {发短信完毕, 发微信完毕, 发QQ完毕};int[] executeTimes new int[]{2, 5, 1};CountDownLatch countDownLatch new CountDownLatch(n);ExecutorService executorService Executors.newFixedThreadPool(n);long start System.currentTimeMillis();for (int i 0; i n; i) {int finalI i;executorService.submit(() - {try {TimeUnit.SECONDS.sleep(executeTimes[finalI]);System.out.println(tasks[finalI]);} catch (InterruptedException e) {e.printStackTrace();} finally {countDownLatch.countDown();}});}countDownLatch.await();System.out.println(所有消息都发送完毕了执行主线程任务。\n耗时ms (System.currentTimeMillis() - start));// 不要忘记关闭线程池不然会导致主线程阻塞无法退出executorService.shutdown();
}本程序利用 CountDownLatch 定义了要等待的子线程数量这样在该统计数量不为0的时候主线代码暂时挂起直到所有的子线程执行完毕调用countDown()方法后主线程恢复执行。