/**
* Thread waiting, similar to the role of thread join
* Suppose 3 threads: 2 T1 and 1 T2, after T1 is executed, T2 is executed again
* In addition to using join to control the execution order of threads, you can also use CountDownLatch to control Sequence of threads
*/
public class CountDownLatchTest {
private AtomicInteger total;
CountDownLatch latch = new CountDownLatch(2);
public static void main(String[] args) {
CountDownLatchTest o = new CountDownLatchTest();
T1 t1 = o.new T1("t1");
T1 t2 = o.new T1("t2");
T2 t3 = o.new T2("t3");
t1.start();
t3.start();
t2.start();
}
class T1 extends Thread{
public T1(String name) {
super(name);
}
public void run() {
System.out.println(this.getName() + " " + System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
}
}
class T2 extends Thread{
public T2(String name) {
super(name);
}
public void run() {
try {
latch.await(); //等待2个T1线程执行完(阻塞直到计数为0)
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName() + " " + System.currentTimeMillis());
}
}
}