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