Java多線程之Phaser基礎篇

在瞭解Phaser之前建議先過一下如下兩篇文章,不瞭解也無妨如果看完有疑問的話可以再過一遍
Java多線程之CyclicBarrier基礎篇
Java多線程之CountDownLatch基礎篇

一、 什麼是Phaser

  • Phaser可以認爲是CyclicBarrier與CountDownLatch的整合,可以用考試做類比,一個班級進行考試必須等所有同學(這裏的同學做題可以看做不同的線程在執行任務)答完題,才能進入下一科考試

二、爲什麼可以將Phaser認爲是CyclicBarrier與CountDownLatch的整合

  • 我們可以回憶一下CountDownLatch講的是先指定N個線程幹完活,在這N個線程幹完活之前,其他線程先等着,CyclicBarrier講的是先指定需要N個線程,等N個線程到齊了大家同時幹活(併發執行),而Phaser正是結合了這二者的特點,可以理解爲先指定N個線程等N個線程到齊了開始幹第一階段的活,等第一階段所有線程幹完活了,接着這N個線程繼續開始幹下一階段的活,以此類推直至幹完業務邏輯了所有階段的活(當然每個階段可以幹完進入下一個階段可以踢掉一下不需要的線程,可以理解完造房子,在後期收尾時就不需要那麼多人了可以辭掉一些,當然也可以全部留下來,不剔除)

三、Phaser代碼示例

public class MyPhaser {
    private static ExamPhaser examPhaser = new ExamPhaser();

    public static void main(String[] args) {
        examPhaser.bulkRegister(5);
        new Thread(new Student(), "學生A").start();
        new Thread(new Student(), "學生B").start();
        new Thread(new Student(), "學生C").start();
        new Thread(new Student(), "學生D").start();
        new Thread(new Student(), "學生E").start();
    }

    static class Student implements Runnable {


        private static void chinese() {
            System.out.println(Thread.currentThread().getName() + "語文考試完畢");
            examPhaser.arriveAndAwaitAdvance();
        }

        private static void math() {
            System.out.println(Thread.currentThread().getName() + "數學考試完畢");
            examPhaser.arriveAndAwaitAdvance();
        }

        private static void english() {
            System.out.println(Thread.currentThread().getName() + "英語考試完畢");
            examPhaser.arriveAndAwaitAdvance();
        }

        private static void history() {
            System.out.println(Thread.currentThread().getName() + "歷史考試完畢");
            examPhaser.arriveAndAwaitAdvance();
        }

        @Override
        public void run() {
            chinese();
            math();
            english();
            history();

        }
    }

    static class ExamPhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0:
                    System.out.println("語文試結束!");
                    return false;
                case 1:
                    System.out.println("數學考試結束!");
                    return false;
                case 2:
                    System.out.println("英語考試結束!");
                    return false;
                case 3:
                    System.out.println("歷史考試結束!");
                    return true;
                default:
                    return true;
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章