I have a thread running when flag is true,but when I change the flag to false, it does not go to die.
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!");
}
}
I know defining "isRunning" as volatile will solve the problem,but when not volatile, "isRunning" shouldn't be visible at some point to MyThread?