Java中CountDownLatch工具类详细解析
创建CountDownLatch对象时,会传入一个count数值,该对象每次调用countDown()方法会使count -- ,就是count每次减1; 调用await()方法,程序会阻塞等待,当count被减到0了之后,await()后面的程序解除阻塞,可以继续运行。 阻塞的是调用await()方法的后续代码,调用countDown()方法count自减1,当count=0 时解除阻塞。 如:
CountDownLatch countDownLatch = new CountDownLatch(4); //初始 count = 4python countDownLatch.countDown(); // count = 4 -1; countDownLatch.countDown(); // count = 3-1; countDownLatch.await(); //当count =0 ,可以执行后续代码
代码示例1: 当count不为0时,程序会一直等待。
import java.util.concurrent.CountDownLatch; public class Test { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(5); new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"已运行!"); countDownLatch.countDown(); } }).start(); countDownLatch.await(); System.out.println(" 程序执行完毕! "); } }
代码示例2:count=0解除阻塞。
import java.util.concurrent.CountDownLatch; public class Test1 { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(5); for(int i = 0 ; i < 5 ; i++){ new Thread(new Runnable() { 编程客栈 @Override public void run() { System.out.println(Thread.currentThread().getName()+"已运行!"); javascriptcountDownLatch.countDown(); } }).start(); } countDownLatch.await(); System.out.println(" 程序执行完毕! "); } }
到此这篇关于Java中androidCountDownLatch工具类详细解析的文章就介绍到这了,更多python相关CountDownLatch工具类内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论