本文提供四个Java并发同步器的代码示例及使用方法,帮助您理解Java多线程编程中的同步机制。
1. CountDownLatch:一次性屏障,协调线程
CountDownLatch允许一个或多个线程等待,直到其他线程完成一组操作。
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int workerCount = 3;
CountDownLatch latch = new CountDownLatch(workerCount);
for (int i = 0; i < workerCount; i++) {
new Thread(() -> {
try {
// 模拟工作
Thread.sleep(1000);
System.out.println("Worker " + Thread.currentThread().getName() + " finished.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); // 完成任务后计数器减一
}
}).start();
}
System.out.println("Main thread waiting for workers to finish...");
latch.await(); // 主线程等待所有计数器变为0
System.out.println("All workers finished. Main thread proceeding.");
}
}
2. Semaphore:控制对共享资源的访问
Semaphore管理一组许可证,控制对有限资源的访问。
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
public static void main(String[] args) {
int permits = 2; // 可用许可证数量
Semaphore semaphore = new Semaphore(permits);
for (int i = 1; i <= 5; i++) {
new Thread(() -> {
try {
semaphore.acquire(); // 获取许可证
System.out.println("Thread " + Thread.currentThread().getName() + " acquired permit.");
// 使用共享资源
Thread.sleep(1000);
System.out.println("Thread " + Thread.currentThread().getName() + " releasing permit.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(); // 释放许可证
}
}).start();
}
}
}
3. CyclicBarrier:可重用的屏障点同步
CyclicBarrier在公共点(屏障)同步多个线程,所有线程到达屏障点后可重复使用。
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
public static void main(String[] args) {
int threadCount = 3;
CyclicBarrier barrier = new CyclicBarrier(threadCount, () -> {
System.out.println("All threads have reached the barrier. Proceeding...");
});
for (int i = 0; i < threadCount; i++) {
new Thread(() -> {
try {
// 模拟工作
Thread.sleep(1000);
System.out.println("Thread " + Thread.currentThread().getName() + " reached the barrier.");
barrier.await(); // 等待其他线程到达屏障
System.out.println("Thread " + Thread.currentThread().getName() + " passed the barrier.");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
4. Phaser:高级动态线程同步
Phaser类似于CyclicBarrier,但支持动态加入和离开线程。
import java.util.concurrent.Phaser;
public class PhaserExample {
public static void main(String[] args) {
Phaser phaser = new Phaser(1); // 注册“主方”
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println("Thread " + Thread.currentThread().getName() + " registered.");
phaser.register(); // 注册线程
try {
Thread.sleep(1000);
System.out.println("Thread " + Thread.currentThread().getName() + " arrived at phase " + phaser.getPhase());
phaser.arriveAndAwaitAdvance(); // 到达并等待其他线程
System.out.println("Thread " + Thread.currentThread().getName() + " passed phase " + phaser.getPhase());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
phaser.arriveAndDeregister(); // 完成并注销
}
}).start();
}
phaser.arriveAndAwaitAdvance(); // 主线程等待所有线程完成第一阶段
System.out.println("All threads finished.");
}
}
这些示例演示了每个同步器的基本用法。您可以修改线程数量和等待时间来观察同步行为的变化。 记住处理潜在的InterruptedException
。