同步块和while循环最优排序

问题描述 投票:2回答:1

如果我在这样的条件下等待(注意:currentAtomicIntegertargetint):

while (current.get() < target) {
    try {
        synchronized (current) {
            current.wait();
        }
    }
    catch (InterruptedException ie) {}
}

然后应该同步进入while(如上所述)或外部,如此?

synchronized (current) {
    while (current.get() < target) {
        try {
            current.wait();
        }
        catch (InterruptedException ie) {}
    }
}

我的问题是,上面两段代码之间的实际/功能差异是什么?何时应该使用另一段代码?

编辑:当另一个线程执行以下操作时退出循环

if (current.incrementAndGet() >= target) {
    synchronized (current) {
        current.notify();
    }
}
java concurrency synchronization synchronized
1个回答
0
投票

它取决于代码的critical section,而不是最佳实践。


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

© www.soinside.com 2019 - 2024. All rights reserved.