1、join:待此线程执行完成后,再执行其他线程,其他线程阻塞等待
CyclicBarrier 等所有线程都到达了就会调用回调,可以用都多个线程计算结果,CyclicBarrier 回调统一计算
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest2 {
static CyclicBarrier c = new CyclicBarrier(2, new A());
public static void main(String[] args) {
//另外的子线程
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + ",19");
System.out.println(1);
c.await();
} catch (Exception e) {
}
}
}).start();
//main线程
try {
System.out.println(Thread.currentThread().getName() + ",28");
System.out.println(2);
c.await();
} catch (Exception e) {
}
}
//所有线程都到达时,最后一个到达的线程触发Runnable运行
static class A implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ",run");
System.out.println(3);
}
}
}
网友评论