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

java CountDownLatch

时间:2016-04-08 11:50:32      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

Listing 6-1. Using a Countdown Latch to Trigger a Coordinated Start
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchDemo
{
    final static int NTHREADS = 3;
    public static void main(String[] args)
    {
        final CountDownLatch startSignal = new CountDownLatch(1);
        final CountDownLatch doneSignal = new CountDownLatch(NTHREADS);
        Runnable r = new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    report("entered run()");
                    startSignal.await(); // wait until told to ...
                    report("doing work"); // ... proceed
                    Thread.sleep((int) (Math.random() * 1000));
                    doneSignal.countDown(); // reduce count on which
                    // main thread is ...
                } // waiting
                catch (InterruptedException ie)
                {
                System.err.println(ie);
                }
            }

            void report(String s)
            {
            System.out.println(System.currentTimeMillis() +
            ": " + Thread.currentThread() +            ": " + s);
            }
        };
        
        ExecutorService executor = Executors.newFixedThreadPool(NTHREADS);
        for (int i = 0; i < NTHREADS; i++)
            executor.execute(r);
            try
            {
                System.out.println("main thread doing something");
                Thread.sleep(1000); // sleep for 1 second
                startSignal.countDown(); // let all threads proceed
                System.out.println("main thread doing something else");
                doneSignal.await(); // wait for all threads to finish
                executor.shutdownNow();
            }
            catch (InterruptedException ie)
            {
            System.err.println(ie);
            }
    }
}

 

java CountDownLatch

标签:

原文地址:http://www.cnblogs.com/rojas/p/5367008.html

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