CountDownLatch同步工具类使用详解同步工具类使用详解
主要为大家详细介绍了CountDownLatch的使用说明,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
CountDownLatch 使用说明,供大家参考,具体内容如下
CountDownLatch是一种java.util.concurrent包下一个同步工具类,它允许一个或多个线程等待直到在其他线程中一组操作执行完成。
CountDownLatch的用法非常简单,下面的例子也是我在网上看到的,十分贴切,这里就贴出来
public class Test {
public static void main(String[] args) {
CountDownLatch begin = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(2);
for(int i=0; i<2; i++){
Thread thread = new Thread(new Player(begin,end));
thread.start();
}
try{
System.out.println("the race begin");
begin.countDown();
end.await();
System.out.println("the race end");
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 选手
*/
class Player implements Runnable{
private CountDownLatch begin;
private CountDownLatch end;
Player(CountDownLatch begin,CountDownLatch end){
this.begin = begin;
this.end = end;
}
public void run() {
try {
begin.await();
System.out.println(Thread.currentThread().getName() + " arrived !");;
end.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
下面是运行结果
可以看到 通过CountDownLatch 的使用 我们控制了线程的执行顺序。
在上面代码中,我们使用到await()方法 和 countDown() 方法 。我们验证一下它们各自的作用。
首先 验证await() 方法。将main方法中的end.await() 注释掉,下面是注释掉后的运行结果
评论0
最新资源