java多线程之CyclicBarrier的用法
解决方法:
1.线程类
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class TestThread extends Thread {
private CyclicBarrier cb
public TestThread(CyclicBarrier cb{
super();
this.cb = cb;
}
@Override
public void run() {
try {
//执行了cb.await()之后这个线程就进入阻塞状态,直到10个线程(由 CyclicBarrier设置)都执行了cb.await()才往下执行
cb.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
2.测试类,
import java.util.concurrent.CyclicBarrier;
public class Run {
public static void main(String[] args) {
CyclicBarrier cb = new CyclicBarrier(10, new Runnable() {
public void run() {
System.out.println("等10个线程都执行了await()方法后,才执行这段代码");
}
});
TestThread[] threads = new TestThread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new TestThread(cb);
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
}
}