美文网首页
CountDownLatch VS CyclicBarrier

CountDownLatch VS CyclicBarrier

作者: zzj0990 | 来源:发表于2021-01-01 01:06 被阅读0次

CountDownLatch - latch.await() 可以理解为门栓,线程每完成一个执行latch.countDown(),即为减1,直至减到0,latch.await() 才会执行,new CountDownLatch(threads.length)设置线程的数量

import java.util.concurrent.CountDownLatch;

public class T06_TestCountDownLatch {
    public static void main(String[] args) {
        usingJoin();
        usingCountDownLatch();
    }

    private static void usingCountDownLatch() {
        Thread[] threads = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threads.length);

        for(int i=0; i<threads.length; i++) {
            threads[i] = new Thread(()->{
                int result = 0;
                for(int j=0; j<10000; j++) result += j;
                latch.countDown();
            });
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("end latch");
    }
    private static void usingJoin() {
        Thread[] threads = new Thread[100];

        for(int i=0; i<threads.length; i++) {
            threads[i] = new Thread(()->{
                int result = 0;
                for(int j=0; j<10000; j++) result += j;
            });
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        for (int i = 0; i < threads.length; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("end join");
    }
}

CyclicBarrier - 循环栅栏,即为满了执行。

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class T07_TestCyclicBarrier {
    public static void main(String[] args) {
        // 参数1:设置待满足的数量条件   参数2:条件满足后 执行的逻辑
        CyclicBarrier barrier = new CyclicBarrier(20, () -> System.out.println("满人,发车"));
        /*CyclicBarrier barrier = new CyclicBarrier(20, new Runnable() {
            @Override
            public void run() {
                System.out.println("满人,发车");
            }
        });*/

        for(int i=0; i<100; i++) {

                new Thread(()->{
                    try {
                        barrier.await();

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }).start();
        }
    }
}
  • 场景 - 不同的线程处理不同的操作,等待三个线程都完成的各自的操作之后,才能进行下一步操作。


    屏幕快照 2021-01-01 上午1.30.51.png

相关文章

网友评论

      本文标题:CountDownLatch VS CyclicBarrier

      本文链接:https://www.haomeiwen.com/subject/vgpdoktx.html