CountDownLatch如其所写,是一个倒计数的锁存器,当计数减至0时触发特定的事件。利用这种特性,可以让主线程等待子线程的结束。下面以一个模拟运动员比赛的例子加以说明。 1 import java.util.concurrent.CountDownLatch; 2 import java.util.concurrent.Executor; 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 6 public class CountDownLatchDemo { 7 private static final int PLAYER_AMOUNT = 5; 8 public CountDownLatchDemo() { 9 // TODO Auto-generated constructor stub 10 } 11 /** 12 * @param args 13 */ 14 public static void main(String[] args) { 15 // TODO Auto-generated method stub 16 //对于每位运动员,CountDownLatch减1后即结束比赛 17 CountDownLatch begin = new CountDownLatch(1); 18 //对于整个比赛,所有运动员结束后才算结束 19 CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT); 20 Player[] plays = new Player[PLAYER_AMOUNT]; 21 22 for(int i=0;i
浅析Java中CountDownLatch用法
最新推荐文章于 2024-09-06 18:50:44 发布