CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。
代码如下:
package Thread;
import java.util.concurrent.CountDownLatch;
/**
*
* @author Cshuzhuo
* @date 2018-03-13
*/
public class MyThreadTest implements Runnable{
private CountDownLatch countDownLatch;
public MyThreadTest(CountDownLatch countDownLatch) {
this.countDownLatch=countDownLatch;
}
public void run() {
System.out.println(Thread.currentThread().getName()+"--子线程执行--");
countDownLatch.countDown();
}
}
package Thread;
import java.util.concurrent.CountDownLatch;
/**
*
* @author Cshuzhuo
* @date 2018-03-13
*/
public class CountDownLatchTest {
public static void main(String[] args) throws Exception {
CountDownLatch count = new CountDownLatch(5);
new Thread(new MyThreadTest(count)).start();
new Thread(new MyThreadTest(count)).start();
new Thread(new MyThreadTest(count)).start();
new Thread(new MyThreadTest(count)).start();
new Thread(new MyThreadTest(count)).start();
count.await();
System.out.println("主线程执行");
}
}
说明:调用await()方法的线程会被一直阻塞,它会等待直到count值为0才继续执行31
countDown() 会让count-1