【JAVA】java中CountDownLatch的用法,实例讲解

来源:互联网 发布:信用卡能买淘宝吗 编辑:程序博客网 时间:2024/05/02 02:11


CountDownLatch主要用于多线程环境中,当所有的线程都countDown了,就会释放所有的等待的线程,await在到0之前一直等待。

直接看一段代码:

package thread.thread;import java.util.concurrent.CountDownLatch;import java.util.concurrent.LinkedBlockingDeque;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;/** * ClassName:CountDownLatchTest <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 2015年7月30日 下午2:04:07 <br/> *  * @author chiwei * @version * @since JDK 1.6 * @see */public class CountDownLatchTest {public static void main(String[] args) {ThreadPoolExecutor poolExe = new ThreadPoolExecutor(100, 1000, 1, TimeUnit.SECONDS,    new LinkedBlockingDeque<Runnable>(100));// 考试开始铃声响起,考试开始final CountDownLatch examBegin = new CountDownLatch(1);// 单个考生,考试结束交卷final CountDownLatch student = new CountDownLatch(10);// 一个考场10位考生for (int i = 0; i < 10; i++) {Runnable runnable = new Runnable() {public void run() {try {System.out.println("考生" + Thread.currentThread().getName() + "在等待考试开始的铃声响起");examBegin.await();System.out.println("考生听到铃声" + Thread.currentThread().getName() + "开始答题");Thread.sleep((long) (Math.random() * 100));//答题过程,真正的业务逻辑处理部分System.out.println("考生" + Thread.currentThread().getName() + "交卷");student.countDown();} catch (Exception e) {e.printStackTrace();}}};poolExe.execute(runnable); // 运动员开始任务}try {// 答题时间Thread.sleep((long) (Math.random() * 10000));System.out.println("考场" + Thread.currentThread().getName() + "开始铃声即将响起");examBegin.countDown(); // 命令计数器置为0System.out.println("考场" + Thread.currentThread().getName() + "考试开始铃声响起");student.await(); // 所有考生交卷System.out.println("考场" + Thread.currentThread().getName() + "考试结束");} catch (Exception e) {e.printStackTrace();}poolExe.shutdown();}}

如以上代码所示,有两个CountDownLatch类,一个控制考场,整个考试的开始和结束,一个控制所有考生是否都交卷了。

examBegin只有在countDown后,10个考生才有可能开始答题,因为答题前有examBegin.await(),会阻塞住;同理,在考试结束前,student.await()会阻塞住,因为只有当所有的学生都交卷了(countDown),await才会通过。

考生pool-1-thread-3在等待考试开始的铃声响起考生pool-1-thread-2在等待考试开始的铃声响起考生pool-1-thread-7在等待考试开始的铃声响起考生pool-1-thread-10在等待考试开始的铃声响起考生pool-1-thread-8在等待考试开始的铃声响起考生pool-1-thread-1在等待考试开始的铃声响起考生pool-1-thread-6在等待考试开始的铃声响起考生pool-1-thread-9在等待考试开始的铃声响起考生pool-1-thread-4在等待考试开始的铃声响起考生pool-1-thread-5在等待考试开始的铃声响起考场main开始铃声即将响起考场main考试开始铃声响起考生听到铃声pool-1-thread-3开始答题考生听到铃声pool-1-thread-10开始答题考生听到铃声pool-1-thread-7开始答题考生听到铃声pool-1-thread-2开始答题考生听到铃声pool-1-thread-8开始答题考生听到铃声pool-1-thread-6开始答题考生听到铃声pool-1-thread-9开始答题考生听到铃声pool-1-thread-1开始答题考生听到铃声pool-1-thread-4开始答题考生听到铃声pool-1-thread-5开始答题考生pool-1-thread-4交卷考生pool-1-thread-8交卷考生pool-1-thread-9交卷考生pool-1-thread-1交卷考生pool-1-thread-10交卷考生pool-1-thread-3交卷考生pool-1-thread-2交卷考生pool-1-thread-6交卷考生pool-1-thread-5交卷考生pool-1-thread-7交卷考场main考试结束
多线程使用场景下,你的CountDownLatch的count值要等于线程数。

等待count个线程全部执行完了,整个任务才算执行结束了。


0 0
原创粉丝点击