- import java.util.concurrent.CountDownLatch;
-
- public class LatchDriverDemo {
- private static final int N = 5;
- public static void main(String[] args) throws InterruptedException {
-
- CountDownLatch startSignal = new CountDownLatch(1);
-
- CountDownLatch doneSignal = new CountDownLatch(N);
- for (int i = 0; i < N; i++)
-
- new Thread(new LatchWorker(startSignal,doneSignal),"t"+i).start();
-
- long start = System.currentTimeMillis();
-
- startSignal.countDown();
-
- startSignal.await();
- long end = System.currentTimeMillis();
-
-
- System.out.println(end+" "+start);
- }
- }
-
- import java.util.concurrent.CountDownLatch;
-
- public class LatchWorker implements Runnable{
- private final CountDownLatch startSignal;
- private final CountDownLatch doneSignal;
- public LatchWorker(CountDownLatch startSignal,CountDownLatch doneSignal){
- super();
- this.startSignal = startSignal;
- this.doneSignal = doneSignal;
- }
- @Override
- public void run() {
- try {
- startSignal.await();
- dowork();
- doneSignal.countDown();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- }
- private void dowork() {
-
- int a = 0 ;
- for (int i = 0; i < 10000; i++) {
- a += 1;
- }
- System.out.println(Thread.currentThread().getName()+"="+a);
- }
-
- }
posted @
2013-05-24 16:03
郑小明
阅读(
283)
评论()
编辑
收藏
举报