【发布时间】:2018-11-23 09:48:18
【问题描述】:
这是我遇到的一个奇怪的情况。我有一个定义受保护字段的抽象基类。还有一个修改字段的公共方法。然后我有一些使用该字段的基类的子类。
我注意到,当我调用超类方法来修改字段时,对字段值的更改似乎并没有“传递”到子类的实例。
需要提到的另一件事是抽象类(以及它的子类)实现了Runnable。我认为这不会影响我所看到的,但多线程不是我的强项。
抽象基类:
public abstract class AbstractWidget implements Runnable {
// Other fields and methods omitted for brevity.
protected boolean running;
public void shutDown() {
running = false;
}
}
子类:
public class ConcreteWidget extends AbstractWidget {
// Other fields and methods omitted for brevity.
@Override
public void run() {
running = true;
while (running) {
// ...
}
logger.info("Shutting down");
}
}
所以,当我最终调用shutDown() 方法时,在线程中运行的子类实例不会中断循环并返回。
我以前多次使用从“外部”修改布尔字段的技术来停止“永久”线程。我不明白这里发生了什么。
更新:
下面是被调用的代码示例。
ConcreteWidget widet = new ConcreteWidget(...);
thread = new Thread(widget);
thread.start();
logger.info("Started");
...
logger.debug("shutting down");
widget.shutDown();
try {
logger.debug("doing join on thread");
thread.join();
logger.debug("returned from join");
} catch (InterruptedException e) {
logger.error("Exception", e);
}
对join() 的调用永远不会返回。
更新:
根据要求,我已经包含了我希望是我目前拥有的代码的完整(足够)示例。注意:我已采纳建议并将受保护的boolean 更改为AtomicBoolean。
public abstract class AbstractWidget implements Runnable {
protected final AtomicBoolean running = new AtomicBoolean(true);
public void shutDown() {
running.set(false);
}
}
public class ConcreteWidget extends AbstractWidget {
@Override
public void run() {
while (running.get()) {
// ... do stuff (including calling process() below)
}
}
private void process() {
try {
// ... do stuff
} catch (IOException e) {
logger.error("Exception", e);
running.set(false);
return;
}
}
}
在“主”逻辑中:
private void startService() {
widget = new ConcreteWidget(...);
thread = new Thread(widget);
thread.start();
logger.info("Started");
}
public void close() {
logger.debug("shutting down service");
widget.shutDown();
try {
logger.debug("doing join on service thread");
thread.join();
logger.debug("returned from join");
} catch (InterruptedException e) {
logger.error("Exception", e);
}
}
顺便说一句,它仍然不起作用。
【问题讨论】:
-
可以分享调用
shutDown()的代码吗?也许问题就在那里。 -
为了简洁起见,您是否无意中在上面
ConcreteWidget中遗漏的代码中声明了protected boolean running;? -
我也这么认为并检查过。不,我没有重新定义子类中的字段。
-
这可能更多的是不使用
volatile/synchronized的问题。 -
将字段类型更改为 AtomicBoolean,使其成为 final,并更改其状态。这保证了其他线程可以看到任何更改。布尔值不会出现这种情况(除非您将其设为易失性,或者您使用相同的锁从同步块中读取和写入它)。 docs.oracle.com/javase/8/docs/api/java/util/concurrent/…