成都网站建设网站制作公司,哪个网站上网好,做微商做什么网站比较好,湖南长沙设计公司学习java多线程#xff0c;请同时参阅 Java多线程 信号量和屏障实现控制并发线程数量#xff0c;主线程等待所有线程执行完毕1 CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后再继续执行。当所有的线程都已经完成任务#xff0c;然后在CountDownLatch上…学习java多线程请同时参阅 Java多线程 信号量和屏障实现控制并发线程数量主线程等待所有线程执行完毕1 CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后再继续执行。当所有的线程都已经完成任务然后在CountDownLatch上等待的线程就可以恢复执行接下来的任务。
代码如下 import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;public class CountDownLatchDemo {public static void main(String[] args) throws InterruptedException {ExecutorService threadPool Executors.newFixedThreadPool(10);final CountDownLatch latch new CountDownLatch(10);for(int i0;i10;i){threadPool.execute(new Runnable(){Overridepublic void run() {try {System.out.println(-----------开始-----j----- );System.out.println(------------threadName--j--- Thread.currentThread().getName());Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}finally {System.out.println(------------threadName--j--- finally Thread.currentThread().getName());System.out.println(---------完成了------j----- );latch.countDown();}}});}latch.await();System.out.println(------------------全部结束------------------ );}}
运行上面测试代码输出如下
-----------开始-----j----- -----------开始-----j----- ------------threadName--j---pool-1-thread-1 -----------开始-----j----- -----------开始-----j----- -----------开始-----j----- ------------threadName--j---pool-1-thread-3 -----------开始-----j----- -----------开始-----j----- ------------threadName--j---pool-1-thread-5 -----------开始-----j----- ------------threadName--j---pool-1-thread-4 ------------threadName--j---pool-1-thread-6 ------------threadName--j---pool-1-thread-7 ------------threadName--j---pool-1-thread-8 -----------开始-----j----- ------------threadName--j---pool-1-thread-2 -----------开始-----j----- ------------threadName--j---pool-1-thread-9 ------------threadName--j---pool-1-thread-10 ------------threadName--j---finallypool-1-thread-6 ------------threadName--j---finallypool-1-thread-5 ------------threadName--j---finallypool-1-thread-8 ---------完成了------j----- ------------threadName--j---finallypool-1-thread-1 ---------完成了------j----- ------------threadName--j---finallypool-1-thread-3 ---------完成了------j----- ------------threadName--j---finallypool-1-thread-2 ---------完成了------j----- ------------threadName--j---finallypool-1-thread-10 ---------完成了------j----- ------------threadName--j---finallypool-1-thread-7 ---------完成了------j----- ---------完成了------j----- ------------threadName--j---finallypool-1-thread-4 ---------完成了------j----- ------------threadName--j---finallypool-1-thread-9 ---------完成了------j----- ---------完成了------j----- ------------------全部结束------------------