CountDownLatch:它是一个辅助类,在完成一组正在其他线程执行的操作之前,它允许线程一直等待。这个类使用一个整数进行初始化,这个线程就是等待完成的操作的数目。当一个线程要等待某些操作先执行完成时,需要调用await()方法,这个方法让线程进入到休眠直到等待的所有操作都完成,当某一个操作完成后,它将调用countDown()方法将CountDownLatch类的内部计数器减1,当计数器变成0的时候,CountDownLatch类将唤醒所有调用await()的方法而进入休眠的线程。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class Student implements Runnable {
private CountDownLatch countDownLatch ;
public Student(CountDownLatch countDownLatch) {
super();
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"来了");
//减少数量
countDownLatch.countDown();
}
}
import java.util.concurrent.CountDownLatch;
public class Teacher implements Runnable{
private CountDownLatch countDownLatch;
public Teacher(CountDownLatch countDownLatch) {
super();
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
System.out.println("人没齐先等人");
try {
countDownLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("人齐了开始上课");
}
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(30);
Thread teacher = new Thread(new Teacher(countDownLatch));
teacher.start();
for(int i=1;i<31;i++){
new Thread(new Student(countDownLatch),"学生"+i).start();
}
}
}
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) { //获取锁 并把数量减一
doReleaseShared();// 如果数量小于0 就唤醒等待的线程
return true;
}
return false;
}
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}