gpt4 book ai didi

java - Phaser 作为 CountdownLatch 的替代品

转载 作者:行者123 更新时间:2023-12-01 19:00:32 26 4
gpt4 key购买 nike

使用 Phaser 替代 CountdownLatch 在性能、内存、改进、稳健性等方面是否有任何好处?

例如,myCountDownLatch() 的行为与 myPhaser() 相同:

带有 CountdownLatch 的版本 1:

public static void myCountDownLatch() {

CountDownLatch countDownLatch = new CountDownLatch(1);
Thread t = new Thread(() ->
{
try {
log.info("CountDownLatch: in thread..");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
});
t.start();
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("CountDownLatch: out thread..");
}

带有 Phaser 的版本 2:

public static void myPhaser() {

Phaser phaser = new Phaser(1);
Thread t = new Thread(() ->
{
try {
log.info("phaser: in thread..");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
phaser.arriveAndDeregister();
});
t.start();
// 1. benefit: With phaser we dont need to manage the InterruptedException ourselves.
phaser.arriveAndAwaitAdvance();
log.info("phaser: out thread..");

}

或者java中的CountdownLatch有更好的替代品吗?

最佳答案

来自https://www.infoq.com/news/2008/07/phasers/

Performance results obtained from a portable implementation of phasers on three different SMP platforms demonstrate that they can deliver superior performance to existing barrier implementations, in addition to the productivity benefits that result from their generality and safety properties.

更多详情请查看JSR 166

关于java - Phaser 作为 CountdownLatch 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59643504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com