如果我正在等待这样的条件(注意:current
是一个 AtomicInteger
而 target
是一个 int
):
while (current.get() < target) {
try {
synchronized (current) {
current.wait();
}
}
catch (InterruptedException ie) {}
}
那么 synchronized 应该进入 while 内部(如上所述)还是外部,就像这样?
synchronized (current) {
while (current.get() < target) {
try {
current.wait();
}
catch (InterruptedException ie) {}
}
}
我的问题是,上面两段代码之间的实际/功能区别是什么?什么时候应该使用其中一段代码?
编辑:当另一个线程执行以下操作时退出循环
if (current.incrementAndGet() >= target) {
synchronized (current) {
current.notify();
}
}
最佳答案
关于java - 同步块(synchronized block)和 while 循环优化排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54669932/