CyclicBarrier簡介
package CyclicBarrier;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
public class TestCyclicBarrier {
private static final int THREAD_NUM = 5;
static AtomicInteger jisu = new AtomicInteger(0);
public static class WorkerThread implements Runnable{
CyclicBarrier barrier;
public WorkerThread(CyclicBarrier b){
this.barrier = b;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
jisu.incrementAndGet();
System.out.println("Worker's waiting");
//线程在这里等待,直到所有线程都到达barrier。
barrier.await();
System.out.println("ID:"+Thread.currentThread().getId()+" Working"+" 最終得出相同的jusu "+jisu);
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
CyclicBarrier cb = new CyclicBarrier(THREAD_NUM, new Runnable() {
//当所有线程到达barrier时执行
@Override
public void run() {
System.out.println("規定綫程數都到達會到達這裏 這裏處理完 其他綫程處理await()後面代碼");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
});
for(int i=0;i<THREAD_NUM;i++){
new Thread(new WorkerThread(cb)).start();
}
}
}
質料 http://www.cnblogs.com/techyc/archive/2013/03/13/2957059.html