gpt4 book ai didi

java - 为什么我将运行标志设置为 false 后线程仍继续运行?

转载 作者:行者123 更新时间:2023-12-01 19:37:51 24 4
gpt4 key购买 nike

当标志为 true 时,我有一个线程正在运行,但是当我将标志更改为 false 时,它​​不会死掉。

public static void main(String[] args)
{
try
{
MyThread mt = new MyThread();
mt.start();
Thread.sleep(1000);
mt.setRunning(false);
System.out.println("set running false");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}

public static class MyThread extends Thread
{
private boolean isRunning = true;

public boolean isRunning()
{
return isRunning;
}

public void setRunning(boolean isRunning)
{
this.isRunning = isRunning;
}

public void run()
{
System.out.println("run");
while (isRunning == true){
}
System.out.println("run over!");
}
}

我知道将“isRunning”定义为 volatile 可以解决问题,但是当不是 volatile 时,“isRunning”在某些时候对 MyThread 不应该可见?

最佳答案

这是由于可见性原因。

使变量可变:

volatile private boolean isRunning = true;

参见What is the volatile keyword useful for了解更多详情。

I know defining "isRunning" as volatile will solve the problem,but when not volatile, "isRunning" shouldn't be visible at some point to MyThread?

这是 isRunning 的值更改,当 main 线程更改它时,您需要使 MyThread 可见。否则它可能只是继续看到 true 的缓存值。

关于java - 为什么我将运行标志设置为 false 后线程仍继续运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56696636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com