一. 实现多线程
1. 虚假的多线程
例1:
public class TestThread { int i=0, j=0; public void go(int flag) { while(true) { try{ Thread.sleep(100); } catch(InterruptedException e) { System.out.println("Interrupted"); } if(flag==0) i++; System.out.println("i=" + i); } else { j++; System.out.println("j=" + j); } } } public static void main(String[] args) { new TestThread().go(0); new TestThread().go(1); } }
上面程序的运行结果为:
i=1 i=2 i=3 。。。
结果将一直打印出I的值。我们的意图是当在while循环中调用sleep()时,另一个线程就将起动,打印出j的值,但结果却并不是这样。关于sleep()为什么不会出现我们预想的结果,在下面将讲到。
|