总体而言,CountDownLatch
用于等待一组线程完成,线程调用CountDownLatch
的await将会阻塞;
而CyclicBarrier
用于等待一组线程达到一个公共屏障点,之后一组线程一起执行。
CountDownLatch(倒计时门栓):
一个门闩,作用是将某个线程关在门外,等门里的人分赃完毕(计数为0)的时候,才会打开门,让外面的那个线程执行。
CountDownLatch
用于等待一个或多个线程完成操作,它在初始化时接收一个计数器,每当一个线程完成任务时,计数器减一,当计数器为零时,等待的线程可以继续执行。countdownlatch表示计数器,可以给countdownlatch设置一个数字,一个线程调用countdownlatch的await将会阻塞,其他线程可以调用countdownlatch的countdown方法来对countdownlatch中的数字减去一,当数字减成0后,所有await的线程都将被唤醒
CyclicBarrier(循环屏障):
回环屏障,像一个水闸, 线程执行就像水流, 在水闸处都会堵住, 等到水满(线程到齐)了, 才开始泄流。
CyclicBarrier
用于等待一组线程达到一个公共屏障点,然后它们可以继续执行,屏障点可以被循环使用。
CountDownLatch:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);
// Worker threads
new Worker(latch, "Thread-1").start();
new Worker(latch, "Thread-2").start();
new Worker(latch, "Thread-3").start();
// Main thread waiting for workers to finish
latch.await();
System.out.println("All workers have finished their tasks.");
}
static class Worker extends Thread {
private CountDownLatch latch;
public Worker(CountDownLatch latch, String name) {
super(name);
this.latch = latch;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is working.");
// Simulate some work
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " has finished.");
// Decrease the latch count
latch.countDown();
}
}
}
CyclicBarrier:
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3, () -> System.out.println("Barrier action executed"));
// Worker threads
new Worker(barrier, "Thread-1").start();
new Worker(barrier, "Thread-2").start();
new Worker(barrier, "Thread-3").start();
}
static class Worker extends Thread {
private CyclicBarrier barrier;
public Worker(CyclicBarrier barrier, String name) {
super(name);
this.barrier = barrier;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is working.");
// Simulate some work
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " has finished.");
try {
// Await other threads to reach the barrier
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}