废话不说直接上代码:
import java.util.concurrent.CountDownLatch;
public class hehed implements Runnable {
private CountDownLatch controller;
public hehed(int number) { // ???
controller = new CountDownLatch(number);
}
public void arrive(String name) {
System.out.println(name + " 名字");
controller.countDown();
System.out.println("------------" + controller.getCount());
}
@Override
public void run() {
System.out.println("第一步主程序跑:");
try {
controller.await();
System.out.printf("全部开始");
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Participant implements Runnable {
private hehed conference;
private String name;
public Participant(hehed conference, String name) {
this.conference = conference;
this.name = name;
}
@Override
public void run() {
System.out.println("第二个:-----");
conference.arrive(name);
}
}
测试类-----------------
public class TestTTTTTTT {
public static void main(String[] args) {
hehed hd=new hehed(9);
Thread threadConference = new Thread(hd); //
threadConference.start();
for(int i=0;i<10;i++){
Participant p = new Participant(hd, "小明"+i);
Thread t = new Thread(p);
t.start();
}
}
}
CountDownLatch有以下基本方法:
1)await(),阻塞等待,直到计数器清零
2)await(int timeout, TimeUnit unit),使线程阻塞,除非被中断或者超过等待的最大时间
如果达到计数器清零,则await返回true,如果等待超过了最大的等待时间,则返回false
简单理解为,先调用await()可以阻塞现成,当await(3) 当现成跑3次后就为0了,之后await阻塞的现成继续跑