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

本文介绍了如何在Java中使用CyclicBarrier和CountDownLatch来实现多个线程同时启动,以复现并发问题。通过创建Worker线程类并结合这两个工具,可以在指定点等待所有线程就绪后再继续执行。
摘要由CSDN通过智能技术生成

【背景】今天遇到一个并发问题,为了在开发环境复现这个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

new Thread(new Worker(cyclicBarrier)).start();

}

}

public static void main(String[] args) throws InterruptedException {

TestCyclicBarrier testCyclicBarrier = new TestCyclicBarrier();

testCyclicBarrier.doTest();

}

}

【方法1结果】

29abdd7e76e1f6602dff2eef83367d3f.png

【方法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

new Thread(new Worker(countDownLatch)).start();

countDownLatch.countDown();

}

}

public static void main(String[] args) throws InterruptedException {

TestCountDownLatch testCountDownLatch = new TestCountDownLatch();

testCountDownLatch.doTest();

}

}

【方法2结果】

5063c2b0e5f8b9cfe133c3cdd34c208a.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值