我有一个类,例如:
public class Test {
private static Thread aThread;
private static Loopy aLoop;
public Test() {
}
public static void main(String[] args) {
startUpdate();
stopUpdate();
startUpdate();
}
public static void startUpdate() {
aLoop = new Loopy();
aThread = new Thread(aLoop);
aThread.start();
}
public static void stopUpdate() {
if (aThread != null) {
aLoop.finish();
}
}
}
可运行的代码如下所示:
public class Loopy implements Runnable {
private static String status = "R"; // Run
public void run() {
while (status.equals("R")) {
// Do Stuff
}
}
public void finish() {
status = "F"; // End Run
}
}
第一次调用startUpdate可以工作。
StopUpdate 按计划运行。
第二次调用 startUpdate 会导致没有完成任何工作,因为状态在停止时仍然等于“F”,即使我正在启动一个新的 Loopy 实例,(对我来说)它的默认值应该是“R” ”。
状态是否跨实例持续存在,或者我是否犯了一个尚未发现的错误?
最佳答案
您过度使用了静态
。
在您的 Loopy
类中,String status
是静态
,因此在所有 Loopy
之间共享实例。
您应该通过删除 static
使 status
成为一个实例变量。
另一个注意事项是,status
也应该是 volatile
,因为它的状态会被许多线程更改而无需同步。
我还建议,也许您也应该在 Test
实例中创建所有变量/方法(main
除外),因为通常最好避免 static
尽可能:
public class Test {
private Thread aThread;
private Loopy aLoop;
public static void main(String[] args) {
final Test test = new Test();
test.startUpdate();
test.stopUpdate();
test.startUpdate();
}
public void startUpdate() {
aLoop = new Loopy();
aThread = new Thread(aLoop);
aThread.start();
}
public void stopUpdate() {
if (aThread != null) {
aLoop.finish();
}
}
}
关于java - 对实例初始化感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19182403/