构造器: public CountDownLatch(int count) {}; //参数count为计数值
3个方法是CountDownLatch类中最重要的方法:
public void await() throws InterruptedException { }; //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { }; //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public void countDown() { }; //将count值减1
package design_pattern;
import java.util.concurrent.CountDownLatch;
import design_pattern.singleton.HungryPattern;
public class CountDownLatchTest {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(2);
System.out.println("程序开始...............");
new Thread() {
@Override
public void run() {
System.out.println("程序进入线程1...............");
Object instance = HungryPattern.getInstance();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + ":" + instance);
latch.countDown();
}
}.start();
new Thread() {
@Override
public void run() {
System.out.println("程序进入线程2...............");
Object instance = HungryPattern.getInstance();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + ":" + instance);
latch.countDown();
}
}.start();
try {
System.out.println("程序等待...............");
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("程序结束...............");
}
}
程序开始...............
程序进入线程1...............
程序等待...............
程序进入线程2...............
1548513253701:java.lang.Object@5a07ae42
1548513253701:java.lang.Object@5a07ae42
程序结束...............