如何自己建网站服务器中国建筑工程平台网
学习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 i=0;i<10;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---==finally==pool-1-thread-6
 ------------threadName--j---==finally==pool-1-thread-5
 ------------threadName--j---==finally==pool-1-thread-8
 ---------完成了------j-----
 ------------threadName--j---==finally==pool-1-thread-1
 ---------完成了------j-----
 ------------threadName--j---==finally==pool-1-thread-3
 ---------完成了------j-----
 ------------threadName--j---==finally==pool-1-thread-2
 ---------完成了------j-----
 ------------threadName--j---==finally==pool-1-thread-10
 ---------完成了------j-----
 ------------threadName--j---==finally==pool-1-thread-7
 ---------完成了------j-----
 ---------完成了------j-----
 ------------threadName--j---==finally==pool-1-thread-4
 ---------完成了------j-----
 ------------threadName--j---==finally==pool-1-thread-9
 ---------完成了------j-----
 ---------完成了------j-----
 ------------------全部结束------------------
