为什么main线程(主线程)不能停止while死循环,而子线程(自定义)可以?多线程大神来

叫练 2020-12-21 03:07:21
/**
* @author :jiaolian
* @date :Created in 2020-12-21 14:01
* @description:死循环不能停止线程情况
* @modified By:
*/
public class CantStopVolatile {

private static boolean notStop = true;

public static void main(String[] args) throws InterruptedException {
PrintString printString = new PrintString();
printString.printString();
printString.setNotStop(false);
}

private static class PrintString extends Thread {
//默认不停止打印;
private boolean notStop = true;

public boolean isNotStop() {
return notStop;
}

public void setNotStop(boolean notStop) {
this.notStop = notStop;
}


public void printString() {
while (notStop) {
try {
System.out.println("ThreadName:"+Thread.currentThread().getName());
//Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}

}
}


疑问:既然主线程和子线程都是线程,按道理来说应该都是一样的,主线程也有自己的栈信息,也是私有内存,当更新notStop为false后,也会把notStop刷新到主内存,预想的程序结果不应该是死循环才对,我测试了新加一个子线程来调用printString方法,子线程是可以正常停止死循环的,也就是说会更新了notStop信息,子线程对notStop可见
...全文
333 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
叫练 2020-12-21
  • 打赏
  • 举报
回复
可以,看错了,后之后据,while循环一直在那里走不了,所以说14行代码一直没自信
kk1924 2020-12-21
  • 打赏
  • 举报
回复
可能你对线程理解有什么出入,,,

有什么想法可以一起交流交流

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧