在我的项目中,我目前使用
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
。这里有一个简短可编译示例。您有任何改进建议吗?
synchronized
,它也会变得更慢。 - ryyst