使用Phaser代替CountdownLatch在性能、内存、改进、健壮性等方面有什么好处吗?
例如,myCountDownLatch()的行为与myPhaser()相同:
版本1与CountdownLatch:
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替代品?
发布于 2020-01-08 10:23:54
来自https://www.infoq.com/news/2008/07/phasers/
在三个不同的SMP平台上实现阶段器的可移植实现所获得的性能结果表明,除了它们的通用性和安全性属性带来的生产力好处之外,它们还可以提供比现有障碍实现更好的性能。
有关更多详细信息,请查看JSR 166
https://stackoverflow.com/questions/59643504
复制相似问题