亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Fork/Join 上下文中的 Phaser 與 CyclicBarrier

Fork/Join 上下文中的 Phaser 與 CyclicBarrier

胡說叔叔 2023-04-26 16:06:25
在嘗試了解 Phaser 和 CyclicBarrier 之間的區別時,我遇到了一些鏈接 Difference between Phaser and CyclicBarrier和 https://www.infoq.com/news/2008/07/phasers/ 我讀到 Phaser 與 Fork/ 兼容Join 接口,而 CyclicBarrier 沒有,這里有一段代碼來演示這一點:移相器 public static void main(String[] args) throws InterruptedException {        CountDownLatch countDownLatch = new CountDownLatch(1);        Phaser phaser = new Phaser(16){            @Override            protected boolean onAdvance(int phase, int registeredParties) {                return phase ==1 || super.onAdvance(phase, registeredParties);            }        };        System.out.println("Available Processors: "+Runtime.getRuntime().availableProcessors());        ExecutorService executorService = ForkJoinPool.commonPool(); // Runtime.getRuntime().availableProcessors() -1        for (int i = 0; i < 16; i++) {            final int count = 0;            executorService.submit(() -> {                while (!phaser.isTerminated()) {                    try {                        Thread.sleep(ThreadLocalRandom.current().nextInt(300, 2000));                        System.out.println(Thread.currentThread().getName() + count + " ... ");                        phaser.arriveAndAwaitAdvance();                        System.out.println(Thread.currentThread().getName() + count + " ... continues ... ");                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }                countDownLatch.countDown();            });        }        countDownLatch.await();    }問題:fork/join 如何通過 Phaser 而不是通過 CyclicBarrier 設法創建更多線程?為什么這些方法arriveAndAwaitAdvance()使線程池創建新線程,以及如何,但方法await()沒有導致線程池創建更多線程?
查看完整描述

1 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

Phaser 之所以能夠做到這一點,是因為它ForkJoinPool.managedBlock(ManagedBlocker)在阻塞線程時會在內部調用。


任何人都可以訪問 ForkJoinPool 的這個 API,因此您可以輕松地增強您的CyclicBarrier版本以使用它,并消除線程饑餓。例如,帶有以下氛圍的東西:


ForkJoinPool.managedBlock(new ManagedBlocker() {


    boolean isReleasable = false;


    @Override

    public boolean block() throws InterruptedException {

        try {

            cyclicBarrier.await();

        } catch (BrokenBarrierException aE) {

            throw new IllegalStateException(aE);

        }

        return isReleasable = true;

    }


    @Override

    public boolean isReleasable() {

        return isReleasable;

    }

});


查看完整回答
反對 回復 2023-04-26
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號