[英]Synchronization as an alternative to a volatile declaration
In this tutorial ( link ) on Java's volatile declaration it is said that the volatile declaration can be an alternative to synchronization. 在有关Java的volatile声明的本教程( 链接 )中,据说volatile声明可以替代同步。
The author's example of a use of the volatile declaration: 作者使用volatile声明的示例:
volatile boolean shutdownRequested;
...
public void shutdown() { shutdownRequested = true; }
public void doWork() {
while (!shutdownRequested) {
// do stuff
}
}
My naive implementation of synchronization would be: 我对同步的幼稚实现是:
volatile boolean shutdownRequested;
...
synchronized public void shutdown() { shutdownRequested = true; }
synchronized public void doWork() {
while (!shutdownRequested) {
// do stuff
}
}
It seems that if thread A invokes shutdown
while thread B has already invoked and is running doWork
it would seem that thread B will continually lock execution, because it is a loop. 似乎如果线程A在线程B已经调用并正在运行
doWork
时调用shutdown
,则似乎线程B将不断锁定执行,因为这是一个循环。 This seems to give no opportunity for thread A to access the boolean. 这似乎没有给线程A访问布尔值的机会。 What did the author have in mind as the synchronized alternative to a volatile declaration?
作为可变声明的同步替代方案,作者想到了什么?
The // do stuff
part would be outside the synchronized block. // do stuff
部分将在同步块之外。 For example, instead of doWork
being synchronized and having while (!shutdownRequested)
, you might have while (!getShutDown())
where getShutDown
is the synchronized method that returns shutdownRequested
. 例如,您可能没有
while (!getShutDown())
而不是让doWork
同步并具有while (!shutdownRequested)
,其中getShutDown
是返回shutdownRequested
的同步方法。
Here's one way it could work: 这是一种可行的方法:
public void doWork() {
while (true) {
synchronized (this) {
if (shutdownRequested) {
break;
}
}
// do stuff
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.