CountDownLatch_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > CountDownLatch

CountDownLatch

 2018/1/25 18:49:55  knight_black_bob  程序员俱乐部  我要评论(0)
  • 摘要:importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassCountDownLatchTest{//比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能publicstaticvoidmain(String[]args
  • 标签:

?

class="java">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/



?
?
?谢谢您的赞助,我会做的更好!

上一篇: ExecutorService 下一篇: Callable 与 Future
  • 相关文章
发表评论
用户名: 匿名