在我的项目中,到目前为止,我使用 CyclicBarrier
来“同步”多个线程(每个线程都运行相同类型的 Runnable
) .在我的例子中,由于同步频率高,使用 CyclicBarrier
被证明是低效的,但忙等待机制可能工作得更快。这是我到目前为止得到的(一些部分被遗漏了):
public class MyRunnable implements Runnable {
private static AtomicInteger counter = null; // initialized to the number
// of threads
public void run() {
// do work up to a "common point"
synchronized (this) {
// decrement the counter and - if necessary - reset it
if (counter.decrementAndGet() == 0) {
counter.set(numberOfThreads);
// make all the busy waiting threads exit from the loop
for (int i = 0; i < threads.length; i++)
threads[i].interrupt();
}
}
// busy wait until all threads have reached the "common point"
while (!Thread.interrupted()) {}
}
}
不幸的是,这段代码的性能比 CyclicBarrier
还要差。 Here's一个简短的、可编译的例子。关于如何改进它有什么建议吗?
最佳答案
如果你有更多的处理器然后你有线程运行,这里的忙等待只会“更快”地工作。如果你不断地在 Thread.interrupted 上旋转并且只是在消耗 CPU 时间,你实际上会显着降低性能。
CyclicBarrier/CountDownLatch 出了什么问题?这似乎是一个更好的解决方案。
关于Java——实现忙等待机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6553044/