以下代码正常工作,即打印Hello!
,直到我按enter
。当我按下输入键时,它停止。如预期的那样,这很好。线程基础知识:为什么相同的代码在不同的类中产生不同的输出?
但是,当我的相同的代码复制到名为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 CLASS: -
编辑: -
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'? '静态'这种方式很有趣 – MadProgrammer
不同的'布尔'。 –
@MadProgrammer为了检查,我改变了'while'循环的条件以及'stopThread()'中的'bool'到'OneDataCached.bool';但是这没有帮助。虽然我认为你的观点非常合理。我编辑了这个问题。 – Solace