3个学生一起参加考试,一共有三道题,要求所有学生到齐才能开始考试,全部同学都做完第一题,学生才能继续做第二题,
全部学生做完了第二题,才能做第三题,所有学生都做完的第三题,考试才结束
public class StudentRunnable implements Runnable{ Phaser phaser = null; String name = null; public StudentRunnable( Phaser phaser , String name ) { this.phaser = phaser; this.name = name; } @Override public void run() { prepare(); phaser.arriveAndAwaitAdvance(); //等待所有的学生到齐 doExercise1(); phaser.arriveAndAwaitAdvance(); //等待所有的学生做完第一道题 doExercise2(); phaser.arriveAndAwaitAdvance(); //等待所有的学生做完第二道题 doExercise3(); phaser.arriveAndAwaitAdvance(); //等待所有的学生做完第三道题 } private void prepare() { try { Thread.sleep(new Random().nextInt(10000)); System.out.println(name + " 准备好了"); } catch (InterruptedException e) { e.printStackTrace(); } } private void doExercise1() { try { Thread.sleep(new Random().nextInt(10000)); System.out.println(name + " 做完第一道题"); } catch (InterruptedException e) { e.printStackTrace(); } } private void doExercise2() { try { Thread.sleep(new Random().nextInt(10000)); System.out.println(name + " 做完第二道题"); } catch (InterruptedException e) { e.printStackTrace(); } } private void doExercise3() { try { Thread.sleep(new Random().nextInt(10000)); System.out.println(name + " 做完第三道题"); } catch (InterruptedException e) { e.printStackTrace(); } } }
/** * boolean onAdvance(int phase, int registeredParties)方法。 * 此方法有2个作用: * 1、当每一个阶段执行完毕,此方法会被自动调用,因此,重载此方法写入的代码会在每个阶段执行完毕时执行, * 2、当此方法返回true时,意味着Phaser被终止,因此可以巧妙的设置此方法的返回值来终止所有线程。 * */ public class Client { public static void main(String[] args) { Phaser phaser = new Phaser(3) { @Override protected boolean onAdvance(int phase, int registeredParties) { switch (phase) { case 0: return studentArrived(); case 1: return finishFirstExercise(); case 2: return finishSecondExercise(); case 3: return finishExam(); default: return true; } } private boolean studentArrived(){ System.out.println("学生准备好了,学生人数:"+getRegisteredParties()); return false; } private boolean finishFirstExercise(){ System.out.println("第一题所有学生做完"); return false; } private boolean finishSecondExercise(){ System.out.println("第二题所有学生做完"); return false; } private boolean finishExam(){ System.out.println("第三题所有学生做完,结束考试"); return true; } }; List <Thread> threads = new ArrayList<>(); IntStream.range(0, 3).forEach(i -> { threads.add(new Thread(new StudentRunnable(phaser, "【学生"+i+"】"))); }); threads.forEach(t -> t.start()); threads.forEach(t -> { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println("考试结束 "+phaser.isTerminated() ); } }