我期待无限循环,但不是,为什么?
I expect infinite loop,but not,why?
这样的代码
测试两种情况
一个是有volatile关键字,可以停止
其他无volatile,线程死循环
public class VolatileTest extends Thread {
public boolean flag = false;
public static void main(String[] args) throws InterruptedException {
VolatileTest volatileTest = new VolatileTest();
volatileTest.start();
Thread.sleep(1000);
volatileTest.flag = true;
}
@Override
public void run() {
while (!flag) {
System.out.println("=====>");
}
}
}
我的错误。问题是您在 while 循环中调用 synchronized
方法。像这样尝试。 Stopped
将永远不会打印,除非您将 flag
重新声明为 volatile
。
public class VolatileTest extends Thread {
public boolean flag = false;
public static void main(String[] args) throws InterruptedException {
VolatileTest volatileTest = new VolatileTest();
volatileTest.start();
Thread.sleep(1000);
volatileTest.flag = true;
System.out.println("flag is now " + flag);
}
@Override
public void run() {
int i = 0;
while (!flag) {
i++;
}
System.out.println("stopped");
}
}
这样的代码
测试两种情况
一个是有volatile关键字,可以停止
其他无volatile,线程死循环
public class VolatileTest extends Thread {
public boolean flag = false;
public static void main(String[] args) throws InterruptedException {
VolatileTest volatileTest = new VolatileTest();
volatileTest.start();
Thread.sleep(1000);
volatileTest.flag = true;
}
@Override
public void run() {
while (!flag) {
System.out.println("=====>");
}
}
}
我的错误。问题是您在 while 循环中调用 synchronized
方法。像这样尝试。 Stopped
将永远不会打印,除非您将 flag
重新声明为 volatile
。
public class VolatileTest extends Thread {
public boolean flag = false;
public static void main(String[] args) throws InterruptedException {
VolatileTest volatileTest = new VolatileTest();
volatileTest.start();
Thread.sleep(1000);
volatileTest.flag = true;
System.out.println("flag is now " + flag);
}
@Override
public void run() {
int i = 0;
while (!flag) {
i++;
}
System.out.println("stopped");
}
}