【发布时间】:2014-07-10 20:53:19
【问题描述】:
以下代码可以正常工作,即在我按下enter 之前,它会打印Hello!。当我按下回车时,它停止了。这很好,正如预期的那样。
但是当我将 相同的代码 复制到另一个名为 OneDataCached 的类中时(所以它只是不同的类的名称)它不能按预期工作。它宁可打印Hello!,当我按下enter 时,它错过了一行,然后再次开始打印hello!
我对为什么会发生这种情况感到困惑,任何提示或指针将不胜感激。
public class One {
static volatile boolean bool=true;
void stopThread(){
bool=false;
}
public static void main(String [] args){
new Thread(new Runnable() {
public void run(){
while(bool){
System.out.println("Hello!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
System.out.println("Press Return to stop ...");
new Scanner(System.in).nextLine();
new One().stopThread();
}
}
将代码复制到 OneDateCached 类后:-
编辑:-
public class OneDataCached {
static volatile boolean bool=true;
void stopThread(){
OneDataCached.bool=false;
}
public static void main(String [] args){
new Thread(new Runnable() {
public void run(){
while(OneDataCached.bool){
System.out.println("Hello!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
System.out.println("Press Return to stop ...");
new Scanner(System.in).nextLine();
new One().stopThread();
}
}
【问题讨论】:
-
您使用的是
OneDataCached.bool还是One.bool?static这种方式很有趣 -
@MadProgrammer 只是为了检查一下,我在
while循环的条件以及stopThread()中将bool更改为OneDataCached.bool;但这并没有帮助。尽管当我考虑到您的观点时,它是非常合法的。我编辑了问题。 -
检查前两个答案,你改错了
bool的状态 -
@SotiriosDelimanolis 我刚试过。没有帮助
-
执行
new OneDataCached().stopThread()以获得您想要的行为。现在,您仍在检查OneDataCached.bool,但正在修改One.bool。
标签: java multithreading thread-safety java.util.scanner volatile