java编程思想笔记-并发之CountDownLatch

时间:2021-10-07 20:51:28

CountDownLatch使用简介

1.CountDownLatch用来同步一个或者多个任务,强制它们等待由其他任务执行的一组操作
2.CountDownLatch设定的初始值只能设置一次,不能重置,使用countDown()来减小这个值,如果希望这个值可以被重置可以使用CycliBarrier

CountDownLatch使用示例

class TaskPortion implements Runnable{
private static int counter=0;
private final int id=counter++;
private static Random rand=new Random(47);
private final CountDownLatch latch;
TaskPortion(CountDownLatch latch){
this.latch=latch;
}
@Override
public void run() {
try {
doWork();
//每调用一次就减小1
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doWork() throws InterruptedException{
TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));
System.out.println(this+"-completed");
}
@Override
public String toString() {
return String.format("%d$ ", id);
}
}

class WaitingTask implements Runnable{
private static int counter=0;
private final int id=counter++;
private final CountDownLatch latch;
WaitingTask(CountDownLatch latch){
this.latch=latch;
}
@Override
public void run() {
try {
//所有的WaitingTask都在这里阻塞,直到CountDownLatch中的值降为0
latch.await();
System.out.println("Latch barrier passed for "+this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

@Override
public String toString() {
return String.format("waitingTask %d ", id);
}
}

public class CountDownLatchDemo {
static final int SIZE=100;
public static void main(String[] args) {
ExecutorService exec=Executors.newCachedThreadPool();
CountDownLatch countDownLatch=new CountDownLatch(SIZE);
for (int i = 0; i < 10; i++) {
exec.execute(new WaitingTask(countDownLatch));
}
for (int i = 0; i < SIZE; i++) {
exec.execute(new TaskPortion(countDownLatch));
}
System.out.println("Latched all tasks");
exec.shutdown();
}
}