【发布时间】:2019-07-07 06:31:01
【问题描述】:
如果我正在等待这样的条件(注意:current 是 AtomicInteger 和 target 是 int):
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();
}
}
【问题讨论】:
-
哪个线程正在递增/递减
current(在代码中看不到,但必须退出循环......)?如果它是另一个线程,您可能需要检查synchronized (current)对其他线程上对current.increment/decrementAndGet的调用的影响。 -
@ernest_k 我已更新问题以显示退出条件。
标签: java concurrency synchronization synchronized