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-02-20 14:59:15 发布