1.Main
/**
* 出发时,导游会在机场收了护照和签证,办理集体出境手续,所以,要等大家都到齐才能出发,出发前再把护照和签证发到大家手里。
对应CyclicBarrier使用。
每个人到达后进入barrier状态。
都到达后,唤起大家一起出发去旅行。
旅行出发前,导游还会有个发护照和签证的动作。
作者:联想桥南
链接:https://www.jianshu.com/p/4ef4bbf01811
来源:简书
*/
public class Main
{
public static void main(String[] args)
{
CyclicBarrier cyclicBarrier=new CyclicBarrier(3,new TourGuideTask());
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.execute(new TraveTask(cyclicBarrier, "哈登", 5));
executor.execute(new TraveTask(cyclicBarrier, "保罗", 3));
executor.execute(new TraveTask(cyclicBarrier, "戈登", 1));
executor.shutdown();
}
}
2. TourGuideTask
public class TourGuideTask implements Runnable
{
@Override
public void run()
{
System.out.println("***** 导游分发护照签证 *****");
try
{
Thread.sleep(2000);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
3. TraveTask
import java.util.concurrent.CyclicBarrier;
public class TraveTask implements Runnable
{
private CyclicBarrier cyclicBarrier;
private String name;
private int arriveTime;
public TraveTask(CyclicBarrier cyclicBarrier, String name, int arriveTime)
{
this.cyclicBarrier = cyclicBarrier;
this.name = name;
this.arriveTime = arriveTime;
}
@Override
public void run()
{
try
{
Thread.sleep(arriveTime * 1000);
System.out.println(name + "到达集合点");
cyclicBarrier.await();
System.out.println(name + "开始旅行啦~~~");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}