Java 并发 - CountDownLatch、CyclicBarrier和Phaser对比
1. CountDownLatch
1.1 CountDownLatch适用场景
1.2 CountDownLatch实例
package com.test.thread;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
int totalThread = 3;
long start = System.currentTimeMillis();
CountDownLatch countDown = new CountDownLatch(totalThread);
for(int i = 0; i < totalThread; i++) {
final String threadName = "Thread " + i;
new Thread(() -> {
System.out.println(String.format("%s\t%s %s", new Date(), threadName, "started"));
try {
Thread.sleep(1000);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(String.format("%s\t%s %s", new Date(), threadName, "ended"));
countDown.countDown();
}).start();;
}
countDown.await();
long stop = System.currentTimeMillis();
System.out.println(String.format("Total time : %sms", (stop - start)));
}
}1.3 CountDownLatch主要接口分析
2. CyclicBarrier
2.1 CyclicBarrier适用场景
2.2 CyclicBarrier实例
2.3 CyclicBarrier主要接口分析
3. Phaser
3.1 Phaser适用场景
3.2 Phaser实例
3.3 Phaser主要接口分析
4. Java进阶系列
最后更新于