Java - 实现忙等待机制

2024-01-18

在我的项目中,到目前为止我已经“同步”了多个线程(每个线程都运行相同类型的Runnable) 用一个CyclicBarrier http://download.oracle.com/javase/6/docs/api/java/util/concurrent/CyclicBarrier.html。就我而言,使用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 http://pastebin.com/4J56v8ii一个简短的、可编译的示例。关于如何改进它有什么建议吗?


如果您的处理器数量多于正在运行的线程,则此处的繁忙等待只会“更快”。如果你不断地在 Thread.interrupted 上旋转并且只是消耗 CPU 时间,你实际上会显着降低性能。

CyclicBarrier/CountDownLatch 出了什么问题?这似乎是一个更好的解决方案。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java - 实现忙等待机制 的相关文章

随机推荐