问题描述
public class TestThread {private static boolean flag = false;public static void main(String[] args) {new Thread() {int i = 0;public void run() {long tm = System.currentTimeMillis();while (!flag) {i++;}System.out.println(System.currentTimeMillis() - tm);}}.start();new Thread() {public void run() {try {Thread.sleep(2000);flag = true;} catch (InterruptedException e) {e.printStackTrace();}}}.start();}} 首先是这样,这样线程永远不会退出,因为线程读到的是旧值,如果给flag加上volatile则会退出。但加了一句打印的语句就奇怪了:public class TestThread {private static boolean flag = false;public static void main(String[] args) {new Thread() {int i = 0;public void run() {long tm = System.currentTimeMillis();while (!flag) {i++;System.out.println(i);}System.out.println(System.currentTimeMillis() - tm);}}.start();new Thread() {public void run() {try {Thread.sleep(2000);flag = true;} catch (InterruptedException e) {e.printStackTrace();}}}.start();}} 如果这样子,即使不加上volatile,线程也会退出,求解。。我的JDK版本是1.6.0_37。
解决方案
类似的问题我之前问过R大http://hllvm.group.iteye.com/group/topic/34932http://hllvm.group.iteye.com/group/topic/34975