Java多線程及其同步實現原理
|
一. 實現多線程
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()為什么不會出現我們預想的結果,在下面將講到。