需求
- 三个子线程,每个子线程执行N个不同的任务,但是这三个子线程分别执行完第N-1个任务后,三个子线程的第N个任务需要同时执行,此时,CyclicBarrie就派上用场了。
具体代码
public class UseCyclicBarrier {
static class Runner implements Runnable {
private CyclicBarrier barrier;
private String name;
public Runner(CyclicBarrier barrier, String name) {
this.barrier = barrier;
this.name = name;
}
@Override
public void run() {
try {
Thread.sleep(1000 * (new Random()).nextInt(5));
System.out.println(name + " 准备OK.");
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(name + " Go!!");
}
}
public static void main(String[] args) throws IOException, InterruptedException {
CyclicBarrier barrier = new CyclicBarrier(3);
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(new Thread(new Runner(barrier, "zhangsan")));
executor.submit(new Thread(new Runner(barrier, "lisi")));
executor.submit(new Thread(new Runner(barrier, "wangwu")));
executor.shutdown();
}
}
需求2
- 如果要求两个线程执行await后,再让另外一个线程-线程三立马执行,线程三执行完了,然后再让上面两个线程执行,代码如下。
public class UseCyclicBarrier02 {
static CyclicBarrier c=new CyclicBarrier(2,new Thread4());
public static void main(String[] args) throws IOException, InterruptedException, BrokenBarrierException {
new Thread(new Runnable() {
@Override
public void run() {
try {
c.await();
System.out.println("这是第一次await之后的输出");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
c.await();
System.out.println("这是第二次await之后的输出");
}
static class Thread4 implements Runnable{
@Override
public void run() {
System.out.println("这是屏障结束后优先执行的方法");
}
}
}
小结
- 上面就是JDK并发包中的CyclicBarrie的简单实用,具体的业务场景请参考小编的下一篇博客。