CountDownLatch是减计数方式,计数==0时释放所有等待的线程;CyclicBarrier是加计数方式,计数达到构造方法中参数指定的值时释放所有等待的线程。
CountDownLatch当计数到0时,计数无法被重置;CyclicBarrier计数达到指定值时,计数置为0重新开始。
CountDownLatch每次调用countDown()方法计数减一,调用await()方法只进行阻塞,对计数没任何影响;CyclicBarrier只有一个await()方法,调用await()方法计数加1,若加1后的值不等于构造方法的值,则线程阻塞。
- import java.util.concurrent.CountDownLatch;
- public class TestConcurrent extends Thread {
- /**
- * CountDownLatch 是并发包中提供的一个可用于控制多个线程同时开始某个动作的类,其
- * 采用的方式为减计数的方式,当计数减至零时位于latch.await()后的代码才会被执行。
- */
- private static CountDownLatch latch = new CountDownLatch(10);
- public static void main(String[] args) {
- long start = System.currentTimeMillis();
- int i = 0;
- while (i < 10) {
- i++;
- new TestConcurrent().start();
- }
- try {
- latch.await();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("use time:" + (System.currentTimeMillis() - start));
- }
- public void run() {
- System.out.println("...");
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- latch.countDown();
- }
- }
import java.util.concurrent.CountDownLatch; public class TestConcurrent extends Thread { /** * CountDownLatch 是并发包中提供的一个可用于控制多个线程同时开始某个动作的类,其 * 采用的方式为减计数的方式,当计数减至零时位于latch.await()后的代码才会被执行。 */ private static CountDownLatch latch = new CountDownLatch(10); public static void main(String[] args) { long start = System.currentTimeMillis(); int i = 0; while (i < 10) { i++; new TestConcurrent().start(); } try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("use time:" + (System.currentTimeMillis() - start)); } public void run() { System.out.println("..."); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } latch.countDown(); } }
- import java.util.concurrent.BrokenBarrierException;
- import java.util.concurrent.CyclicBarrier;
- import java.util.concurrent.TimeUnit;
- import java.util.concurrent.TimeoutException;
- public class TestCyclicBarrier extends Thread {
- /**
- * CyclicBarrier 和CountDownLatch不同,CyclicBarrier是当await 的数量达到了设置的数量后,
- * 才继续往下执行
- */
- static CyclicBarrier cyclicBarrier = new CyclicBarrier(10);
- private int id;
- public TestCyclicBarrier(int id) {
- this.id = id;
- }
- public static void main(String[] args) {
- long start = System.currentTimeMillis();
- int i = 0;
- while (i < 10) {
- i++;
- new TestCyclicBarrier(i).start();
- }
- System.out.println("use time:" + (System.currentTimeMillis() - start));
- }
- public void run() {
- try {
- System.out.println("----start:" + id);
- cyclicBarrier.await(1000, TimeUnit.MILLISECONDS);
- System.out.println("----start__:" + id);
- } catch (InterruptedException e1) {
- e1.printStackTrace();
- } catch (BrokenBarrierException e) {
- e.printStackTrace();
- } catch (TimeoutException e) {
- e.printStackTrace();
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("----end:" + id);
- }
- }