闭锁(CountDownLatch)
是Java中的一个同步辅助类,用于协调多个线程之间的协作。它允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。闭锁非常适用于需要等待一组事件发生之后再执行某些操作的场景。
import java.util.concurrent.CountDownLatch;public class CountDownLatchExample {public static void main(String[] args) throws InterruptedException {int threadCount = 3;CountDownLatch latch = new CountDownLatch(threadCount);for (int i = 0; i < threadCount; i++) {new Thread(new Worker(latch)).start();}latch.await(); // 主线程等待所有工作线程完成System.out.println("所有工作线程已完成。");}
}class Worker implements Runnable {private final CountDownLatch latch;Worker(CountDownLatch latch) {this.latch = latch;}@Overridepublic void run() {try {// 模拟工作线程执行任务Thread.sleep((long) (Math.random() * 1000));System.out.println(Thread.currentThread().getName() + " 完成任务。");} catch (InterruptedException e) {Thread.currentThread().interrupt();} finally {latch.countDown(); // 任务完成,计数器减1}}
}
import java.util.concurrent.CountDownLatch;public class ConcurrentTaskExample {public static void main(String[] args) throws InterruptedException {int threadCount = 5;CountDownLatch startSignal = new CountDownLatch(1);CountDownLatch doneSignal = new CountDownLatch(threadCount);for (int i = 0; i < threadCount; i++) {new Thread(new Task(startSignal, doneSignal)).start();}System.out.println("准备开始...");startSignal.countDown(); // 所有线程同时开始doneSignal.await(); // 等待所有线程完成System.out.println("所有任务已完成。");}
}class Task implements Runnable {private final CountDownLatch startSignal;private final CountDownLatch doneSignal;Task(CountDownLatch startSignal, CountDownLatch doneSignal) {this.startSignal = startSignal;this.doneSignal = doneSignal;}@Overridepublic void run() {try {startSignal.await(); // 等待开始信号// 模拟任务执行Thread.sleep((long) (Math.random() * 1000));System.out.println(Thread.currentThread().getName() + " 执行任务。");} catch (InterruptedException e) {Thread.currentThread().interrupt();} finally {doneSignal.countDown(); // 任务完成,计数器减1}}
}
跳转到:
栅栏(CyclicBarrier)
信号量(Semaphore)