一天,一個起地基接到一個工程項目,找了砌磚的和切木的,想湊活把項目作下來,項目前,須要規劃,大夥起名叫盒馬工程,計劃分三期java
先找組建幹活的工人ide
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); } }
安排進度計劃this
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("-------------------盒馬總工程按時交付----------"); } }