一天,一个起地基接到一个工程项目,找了砌砖的和切木的,想凑活把项目做下来,项目前,需要规划,大伙起名叫盒马工程,计划分三期
先找组建干活的工人
public class OrderRunnable implements Runnable { private Integer time; private String name; /** * 线程循环器 */ private CyclicBarrier cyclicBarrier; /** * 子线程执行完,同步回到主线程计数 */ private CountDownLatch latch; private List<String> listDo; public OrderRunnable(CountDownLatch latch, List<String> listDo, String name, Integer time, CyclicBarrier cyclicBarrier) { this.time = time; this.name = name; this.latch = latch; this.listDo = listDo; this.cyclicBarrier = cyclicBarrier; } @Override public void run() { for (int i = 0; i < listDo.size(); i++) { try { OrderDataChannel.action(listDo.get(i)); String thName = Thread.currentThread().getName(); System.out.println(name+"---working start---"+thName); Thread.sleep(time); System.out.println(name+"---working finish---"+thName); System.out.println(listDo.get(i)+"---"+name+"---完工---休假中---"); cyclicBarrier.await(); }catch (Exception e){ System.out.println(e); } } latch.countDown(); } }
public class OrderThread extends Thread { public OrderThread(OrderRunnable target) { super(target); } }
安排进度计划
public class OrderDataChannel { public static int count = 0; public static synchronized void action(String stage){ List<String> stages = ThreadClient.listDo; for (int i = 0; i < stages.size(); i++) { if (stages.get(i).equals(stage) && i == count){ System.out.println("-------------------盒马工程"+stage+"开始----------"); count++; } } } }
开始工作
public class ThreadClient { public static final List<String> listDo = Arrays.asList("1期", "2期", "3期"); public static void main(String[] args) throws InterruptedException{ CyclicBarrier barrier = new CyclicBarrier(3); CountDownLatch latch = new CountDownLatch(3); System.out.println("-------------------盒马总工程开始----------"); OrderRunnable orderRunnable = new OrderRunnable(latch, listDo, "砌砖工",3000, barrier); OrderThread orderThread = new OrderThread(orderRunnable); orderThread.start(); OrderRunnable orderRunnable1 = new OrderRunnable(latch, listDo,"木工",4000, barrier); OrderThread orderThread1 = new OrderThread(orderRunnable1); orderThread1.start(); OrderRunnable orderRunnable2 = new OrderRunnable(latch, listDo,"地基工",1000, barrier); OrderThread orderThread2 = new OrderThread(orderRunnable2); orderThread2.start(); latch.await(); System.out.println("-------------------盒马总工程按时交付----------"); } }