CountDownLatch源码解析添加链接描述
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) {
CountDownLatch count = new CountDownLatch(10);
for(int i=0;i<10;i++){
new Thread(new one(count)).start();
}
for(int i=0;i<10;i++){
new Thread(new two(count)).start();
}
}
}
class one implements Runnable{
private CountDownLatch count;
one(CountDownLatch count){
this.count = count;
}
@Override
public void run() {
try {
count.await();
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class two implements Runnable{
private CountDownLatch count;
two(CountDownLatch count){
this.count = count;
}
@Override
public void run() {
count.countDown();
System.out.println("two"+Thread.currentThread().getName());
}
}
CountDownLatch begin = new CountDownLatch(10),表明初始时AQS的state=10。当有线程中调begin.await()时,就是将当前线程阻塞,直到其余的线程中使用begin.countDown()将state减为0时,被阻塞的线程会按照阻塞进入AQS队列的顺序进行唤醒并执行。
当线程中调用begin.countDown()一次就会将state的状态减1(当中是利用CAS来减的)。