欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CountDownLatch 博客分类: java concurrent CountDownLatchjavaconcurrent 

程序员文章站 2024-03-06 19:24:02
...

 

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchTest {

	//比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能 
 public static void main(String[] args) throws InterruptedException {
	 ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
	 int num = 10;
	 CountDownLatch cdl = new CountDownLatch(num);
	 long start = System.currentTimeMillis();
	 for (int i = 0; i < num; i++) {
		 newFixedThreadPool.submit(new CountDownLatchRunnable(cdl));
	}
	 cdl.await();
    //TODO: 等待所有线程结束 做统计
	 long end = System.currentTimeMillis();
	 System.out.println((end-start)/1000);
	 newFixedThreadPool.shutdown();
 }
 
 public static class CountDownLatchRunnable implements Runnable{

	 private CountDownLatch cdl;
	 
	 public CountDownLatchRunnable(CountDownLatch cdl){
		 this.cdl = cdl; 
	 }
	 
	@Override
	public void run() {
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) { 
			e.printStackTrace();
		}
		cdl.countDown();
	}
	 
 }
 

}

 

//回环栅栏,通过它可以实现让一组线程等待至某个状态之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用。我们暂且把这个状态就叫做barrier,当调用await()方法之后,线程就处于barrier了。
 public static void main(String[] args) throws InterruptedException {
	 ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
	 int num = 10;
	 CountDownLatch cdl = new CountDownLatch(1); 
	 for (int i = 0; i < num; i++) {
		 newFixedThreadPool.submit(new CountDownLatchRunnable2(cdl));
	}
	 System.out.println("===========");
	 cdl.countDown(); 
	 
	 // 该实例时做压测是同时处理,起到高并发作用
	 newFixedThreadPool.shutdown();
 }
 
 public static class CountDownLatchRunnable2 implements Runnable{

	 private CountDownLatch cdl;
	 
	 public CountDownLatchRunnable2(CountDownLatch cdl){
		 this.cdl = cdl; 
	 }
	 
	@Override
	public void run() {
		
		try {
			cdl.await(); 
			 System.out.println("==================== ====="+System.currentTimeMillis());
		} catch (InterruptedException e) { 
			e.printStackTrace();
		}
		
	}
	 
 }
 

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者 

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。

 

个人主页http://knight-black-bob.iteye.com/


CountDownLatch 
            
    
    博客分类: java concurrent CountDownLatchjavaconcurrent CountDownLatch 
            
    
    博客分类: java concurrent CountDownLatchjavaconcurrent CountDownLatch 
            
    
    博客分类: java concurrent CountDownLatchjavaconcurrent 
 
 
 谢谢您的赞助,我会做的更好!