如下代码一;
public class Stopdemo {
//public volatile static boolean stop = false;
public static boolean stop = false;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new StopThread());
t1.start();
TimeUnit.SECONDS.sleep(2);
stop = true;
System.out.println("赋值 stop = true");
}
static class StopThread implements Runnable{
@Override
public void run() {
int i = 0;
while(!stop) { //while(true)
i++;
}
System.out.println("运行结束: "+i);
}
}
}
运行结果为:线程不会中止推出一直循环
而若在子线程的while循环中加入System.out.println("运行中"); 则程序运行 一会后会 自动正常
Process finished with exit code 0 似乎是 赋值 stop = true 生效了导致 线程运行结束, 大神帮忙解答一下为什么 谢谢
public class Stopdemo {
//public volatile static boolean stop = false;
public static boolean stop = false;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new StopThread());
t1.start();
TimeUnit.SECONDS.sleep(2);
stop = true;
System.out.println("赋值 stop = true");
}
static class StopThread implements Runnable{
@Override
public void run() {
int i = 0;
while(!stop) { //while(true)
i++;
System.out.println("运行中");
}
System.out.println("运行结束: "+i);
}
}
}