码迷,mamicode.com
首页 > 编程语言 > 详细

java计数器CountDownLatch

时间:2017-01-14 23:21:01      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:random   public   runnable   bsp   trace   cache   pack   ext   latch   

CountDownLatch里面有个属性为state,当为零时触发代码往下执行,代码如下:

package threadLock;

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

public class CountDownLatchTest {

    public static void main(String[] args) {
        final CountDownLatch latch1 = new CountDownLatch(1);
        final CountDownLatch latch2 = new CountDownLatch(3);
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < 3; i++) {
            service.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        System.out.println("线程"
                                + Thread.currentThread().getName() + "正在等待命令。");
                        latch1.await();
                        System.out.println("线程"
                                + Thread.currentThread().getName() + "正在处理。");
                        Thread.sleep(new Random().nextInt(1000));
                        latch2.countDown();

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        try {
            Thread.sleep(1000);

            System.out.println("thread main 发布命令。");
            System.out.println("thread main 正在收集各线程响应。");
            latch1.countDown();

            latch2.await();
            System.out.println("thread main已收集所有线程的响应。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

java计数器CountDownLatch

标签:random   public   runnable   bsp   trace   cache   pack   ext   latch   

原文地址:http://www.cnblogs.com/zhouquan-1992-04-06/p/6286304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!