public class CountDownLatchApp {
public CountDownLatch countDownLatch = new CountDownLatch(100);
public Semaphore semaphore = new Semaphore(1);
public CyclicBarrier cyclicBarrier = new CyclicBarrier(100);
public static void main(String[] args) throws Exception {
cyclicBarrierTest();
countDownLatchTest();
semaphoreTest();
}
public static void cyclicBarrierTest() throws Exception {
final CountDownLatchApp app = new CountDownLatchApp();
for (int i = 0; i < 99; i++) {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
app.cyclicBarrier.await();
System.out.println(Thread.currentThread().getName() + "await");
} catch (Exception e) {
}
}
}).start();
}
System.out.println("Main");
app.cyclicBarrier.await();
System.out.println("MainEnd");
}
public static void countDownLatchTest() throws Exception {
final CountDownLatchApp app = new CountDownLatchApp();
for (int i = 0; i < 99; i++) {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
app.countDownLatch.countDown();
} catch (Exception e) {
}
}
}).start();
}
System.out.println("Main");
app.countDownLatch.countDown();
app.countDownLatch.await();
System.out.println("MainEnd");
}
public static void semaphoreTest() throws Exception {
final CountDownLatchApp app = new CountDownLatchApp();
for (int i = 0; i < 99; i++) {
new Thread(new Runnable() {
public void run() {
try {
app.semaphore.acquire();
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
app.semaphore.release();
} catch (Exception e) {
}
}
}).start();
}
app.semaphore.acquire();
System.out.println("Main");
System.out.println("MainEnd");
app.semaphore.release();
}
}Java并发编程 CountDownLatch,Semaphore,CyclicBarrier
最新推荐文章于 2025-10-17 21:56:51 发布
本文通过三个实例详细介绍了Java中三种重要的并发控制机制:CountDownLatch、Semaphore及CyclicBarrier的使用方法。CountDownLatch允许一个或多个线程等待其他线程完成操作;Semaphore用于控制对资源的访问数量;CyclicBarrier则让所有线程达到屏障点后继续运行。
798

被折叠的 条评论
为什么被折叠?



