一个容易疏忽的多线程程序陷阱

发表于:2007-06-11来源:作者:点击数: 标签:
注意这段代码: public class Demo{public static void main(String[] args) { MyRunnable r=new MyRunnable(); new Thread(r).start();// Thread one r.cache=false; new Thread(r).start();// Thread two } } class MyRunnable implments Runnable { boole

注意这段代码:

public class Demo{public static void main(String[] args)

{

 MyRunnable r=new MyRunnable();

new Thread(r).start();// Thread one

r.cache=false;

new Thread(r).start();// Thread two

}

}

class MyRunnable implments Runnable {

boolean cache=true;

public void run()

{

  while(true)

{

 if(cache)

 System.out.println("this is thread one!");

 else

System.out.println("this is thread two!");

}

}

}

也许我们要达到的效果是:交错打印"this is Thread one!"和"this is Thread two!";但是事实上却总是打印"this is Thread two!";

为什么会出现上面的现象呢?因为主线程享有一个时间片,如果一个时间片足够长,那么当执行了 new Thread(r).start();// Thread one这句后,主线程继续在运行,Thread one 将被迫等待,也就是说这个线程并没有运行;当执行了 r.cache=false;以及后面的 new Thread(r).start();// Thread two后,主线程结束,这时候等待已久的Thread one运行起来,可是这个时候它看见的r.cache并不是我们想要的true,而已经在主线程中被修改成了false,所以Thread one 和Thread two 都只会打印"this is Thread two!".



原文转自:http://www.ltesting.net

...