Java 同步块和while循环优化排序

Java 同步块和while循环优化排序,java,concurrency,synchronization,synchronized,Java,Concurrency,Synchronization,Synchronized,如果我正在等待这样的条件(注意:current是一个AtomicInteger,target是一个int): 这取决于代码的内容,而不是最佳实践 但是,最好将临界段代码长度保持在最小值,因为一次只允许一个线程进入。否则,为了达到极限,您可以同步整个程序并使其安全。哪个线程正在递增/递减当前的(代码中没有看到,但循环必须退出…)?如果是另一个线程,您可能需要检查synchronized(current)对在其他线程上调用current.increment/decrementAndGet的效果。@

如果我正在等待这样的条件(注意:
current
是一个
AtomicInteger
target
是一个
int
):


这取决于代码的内容,而不是最佳实践



但是,最好将临界段代码长度保持在最小值,因为一次只允许一个线程进入。否则,为了达到极限,您可以同步整个程序并使其安全。

哪个线程正在递增/递减当前的
(代码中没有看到,但循环必须退出…)?如果是另一个线程,您可能需要检查
synchronized(current)
对在其他线程上调用
current.increment/decrementAndGet
的效果。@ernest_k我已经更新了问题以显示退出条件。@SinaMadani:…如果该选项在其他方面是正确的。尽管它减小了“关键部分”的大小我确实想知道每次执行循环时重新获取锁是否有任何开销?无论哪种方式,理论上,条件最多只能计算两次,所以我认为这无关紧要?@SinaMadani:无论您是在循环内部还是外部获得锁,代码复杂度都将是O(n)。可能会有开销,但它不会改变大O。可以肯定的是,评测代码并测量时间。
while (current.get() < target) {
    try {
        synchronized (current) {
            current.wait();
        }
    }
    catch (InterruptedException ie) {}
}
synchronized (current) {
    while (current.get() < target) {
        try {
            current.wait();
        }
        catch (InterruptedException ie) {}
    }
}
if (current.incrementAndGet() >= target) {
    synchronized (current) {
        current.notify();
    }
}