|
注意这段代码: 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!".
|