CountDownLatch
CountDownLatch是一个同步工具类,用来协调多个线程之间的同步
CountDownLatch能够使一个线程等待另一些线程完成各自任务之后,再执行。
CountDownLatch实现
这个地方mutexLock是一个用信号量构造的互斥锁,主要是保护共享变量的。详见 利用信号量来实现读写锁
构造函数接受一个整数。是一个计数器。
这个latch设置信号量的初始值是0。这样当A线程运行await函数时,他就会立即阻塞。
当其他线程运行down函数(相对于CountDownLatch中的countdown函数)count就减减,直到count等于0时。表明所有线程执行完毕。就释放锁。唤醒A线程。
public class MyCountDownLatch {
private Semaphore latch = new Semaphore(0);
private MutexLock mutex = new MutexLock();
private int count;
MyCountDownLatch(int i){
count = i;
}
public void await() throws InterruptedException{
latch.acquire();
}
public void down() throws InterruptedException {
mutex.lock();
count--;
if(count == 0){
latch.release();
}
mutex.unlock();
}
}
测试代码
public class Main {
public static void main(String[] args){
new Main().test();
}
private void test(){
int num = 5;
MyCountDownLatch latch = new MyCountDownLatch(num);
for(Integer i = 0; i < num; i++){
new MyThread(latch,i.toString()).start();
}
try {
latch.await();
}catch (Exception e){
}
System.out.println("all done");
}
class MyThread extends Thread{
private MyCountDownLatch latch;
public MyThread(MyCountDownLatch l,String name){
latch = l;
this.setName(name);
}
public void run(){
try{
System.out.println(this.getName() + " is running");
Thread.sleep((int)(Math.random() * 5000));
System.out.println(this.getName() + " done");
latch.down();
}catch (Exception e){
}
}
}
}
测试的结果
0 is running
3 is running
1 is running
2 is running
4 is running
2 done
0 done
1 done
4 done
3 done
all done
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。