您的位置:首页 > 编程语言 > Java开发

[置顶] Java并发编程 CountDownLatch,Semaphore,CyclicBarrier

2017-04-08 22:20 295 查看
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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: