java多线程与while循环的问题

java中,我用线程A去修改class1.filed1,main线程中有一段代码是这样的:
while(class1.filed1 == null){

}
如上代码,程序会死在while循环中,但是在while里添加线程休眠后正常,代码如下:
while(class1.filed1 == null){
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
请问这是什么原因呢?

另外,第一段代码在window+jdk1.6(开发时候环境)没问题,在linux+jdk1.7中有问题。

public class TestInterrupt {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
try {
Thread.sleep(1000);//1.main线程sleep,跳到mt线程。
System.out.println(Thread.currentThread().getName()//4.跳回来继续
+ " is running");
} catch (InterruptedException e) {
}
mt.flag = false;//5.令flag = false,main线程结束,跳到mt线程
}
}

class MyThread extends Thread {
boolean flag = true;

public void run() {
while (flag) {//2.此时flag为true,进入循环    //7.判断flag为false,不循环了。。。
System.out.println(Thread.currentThread().getName()
+ " is running");
System.out.println("----" + new Date() + "----");
try {
sleep(2000);//3.mt线程sleep,跳到main线程
System.out.println(flag);//6.跳回来继续
System.out.println("***" + Thread.currentThread().getName()
+ " is running" + "***");
} catch (InterruptedException e) {
break;
}
}
}
}

追问

感谢您的回答,看了您的代码,我理解,您的意思是当执行Thread.sleep(1000);的时候,执行的线程是切换的,但是,不睡眠,似乎线程也会切换啊?而且,似乎和运行环境还有关系。。。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-05-22
主线程 不 休眠 会儿 其他线程 也没法执行追问

那为什么window下没问题呢?而且,线程之间不是互相抢时间片段吗?通过log,我确定,其他线程执行了,class1.filed1的值已经不为null了,在其他线程里做的修改,并打印的日志。

相似回答