java.util.concurrent.CountDownLatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,计数器大于0 时,await()方法会阻塞程序继续执行。
1.构造方法参数指定了计数的次数
2.countDown方法,当前线程调用此方法,则计数减一
3.awaint方法,调用此方法会一直阻塞当前线程,直到计时器的值为0
package cn.baokx; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; class SubThread implements Runnable{ private CountDownLatch downLatch; private String name; public SubThread(CountDownLatch downLatch,String name){ this.downLatch = downLatch; this.name = name; } @Override public void run() { System.out.println(this.name+" is working..."); try { TimeUnit.SECONDS.sleep(new Random().nextInt(10)); System.out.println(this.name + " has finished its working..."); } catch (InterruptedException e) { e.printStackTrace(); }finally{ this.downLatch.countDown(); } } } public class CountDownLatchTest { public static void main(String[] args) { CountDownLatch downLatch = new CountDownLatch(4); SubThread st1 = new SubThread(downLatch,"subThread1"); SubThread st2 = new SubThread(downLatch,"subThread2"); SubThread st3 = new SubThread(downLatch,"subThread3"); SubThread st4 = new SubThread(downLatch,"subThread4"); System.out.println("MainThread is wating..."); new Thread(st1).start(); new Thread(st2).start(); new Thread(st3).start(); new Thread(st4).start(); try { downLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("All subThread has finished,MainThread can begin to checking..."); } }
时间: 2024-11-05 17:27:24