java多个线程同时启动的两种方式

2021-10-02 00:00:00 多个 线程 两种

【背景】今天遇到一个并发问题,为了在开发环境复现这个bug,需要让多个线程同时执行到某条语句。

【解决方案】
java1.5的concurrent包下的CyclicBarrier 和 CountDownLatch都能解决这个问题。不得不佩服Doug Lea!

【方法1】使用CyclicBarrier

public class TestCyclicBarrier {

    class Worker implements Runnable{

        CyclicBarrier cyclicBarrier;

        public Worker(CyclicBarrier cyclicBarrier){
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                cyclicBarrier.await(); // 等待其它线程
                System.out.println(Thread.currentThread().getName() + "启动@" + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    public void doTest() throws InterruptedException {
        final int N = 5; // 线程数
        CyclicBarrier cyclicBarrier = new CyclicBarrier(N);
        for(int i=0;i<N;i++){
            new Thread(new Worker(cyclicBarrier)).start();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TestCyclicBarrier testCyclicBarrier = new TestCyclicBarrier();
        testCyclicBarrier.doTest();
    }
}

【方法1结果】
《java多个线程同时启动的两种方式》

【方法2】使用CountDownLatch

package thread;

import java.util.concurrent.CountDownLatch;

public class TestCountDownLatch {

    class Worker implements Runnable{

        CountDownLatch countDownLatch;

        Worker(CountDownLatch countDownLatch){
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            try {
                countDownLatch.await(); // 等待其它线程
                System.out.println(Thread.currentThread().getName() + "启动@" + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void doTest() throws InterruptedException {
        final int N = 5; // 线程数
        CountDownLatch countDownLatch = new CountDownLatch(N);
        for(int i=0;i<N;i++){
            new Thread(new Worker(countDownLatch)).start();
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TestCountDownLatch testCountDownLatch = new TestCountDownLatch();
        testCountDownLatch.doTest();
    }
}

【方法2结果】
《java多个线程同时启动的两种方式》

    原文作者:7im0thyZhang
    原文地址: https://blog.csdn.net/timothytt/article/details/86618318
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章