CountDownLatch 类跟CyclicBarrier类似,通过countDown()方法递减,直到为零,所有被它阻塞的线程被唤起执行。
1 package net.vincent.study.other;
2
3 import java.util.concurrent.CountDownLatch;
4
5 public class part2 {
6 public static void main(String[] agrs){
7 CountDownLatch countDownlatch = new CountDownLatch(2);
8 new testThread("threadOne",countDownlatch).start();
9 new testThread("threadOne",countDownlatch).start();
10
11
12 }
13 }
14 class testThread extends Thread {
15 CountDownLatch countDownlatch;
16 public testThread(String threadName,CountDownLatch countDownlatch){
17 super(threadName);
18 this.countDownlatch = countDownlatch;
19 }
20 public void run(){
21 System.out.print(this.getName()+" running ");
22 try {
23
24 countDownlatch.countDown();
25 System.out.println("count is "+countDownlatch.getCount());
26 countDownlatch.await();
27 } catch (InterruptedException e) {
28 e.printStackTrace();
29 }
30 System.out.println(this.getName()+" Done");
31 }
32 }
33