日期:2014-05-20  浏览次数:20658 次

求教多线程


package thread;
class MyThread extends Thread{
public MyThread(String name){
super(name);
}
public void run(){
System.out.println(getName() + " -  Begin...");
for(int i = 0;i < 10;i++){
System.out.println(getName() + " - " + i);
try{
sleep(500);
}catch (InterruptedException e){

}
}
System.out.println(getName() + " - End...");
}
}
public class Test {


public static void main(String[] args) {
MyThread t1 = new MyThread("THread One");
MyThread t2 = new MyThread("THread Two");
t1.start();
t2.start();
}

}
本来是应该xxx one xxx two轮流打印的,但有时候会打印如下结果或者其他什么看上去不是很正常的结果是什么原因啊?
THread One -  Begin...
THread One - 0
THread Two -  Begin...
THread Two - 0
THread One - 1
THread Two - 1
THread One - 2
THread Two - 2
THread Two - 3
THread One - 3
THread One - 4
THread Two - 4
THread Two - 5
THread One - 5
THread Two - 6
THread One - 6
THread One - 7
THread Two - 7
THread Two - 8
THread One - 8
THread One - 9
THread Two - 9
THread Two - End...
THread One - End...

------解决方案--------------------
本来就是两个互不干扰的线程,打印结果的顺序应该也是随机的,加个同步标识试试。
------解决方案--------------------
每个线程占用CPU的时间是不固定的,同样也不一定是相等的
------解决方案--------------------
线程本身就具有无序性,就像2个不懂事的孩子一样同时要抢一样东西,这样谁也说不准谁会抢到。
当时我们给孩子规矩,让他们按照我们的意愿去执行,那就不一样了,比如说让孩子A先拿,孩子B等待,等孩子A玩好了,通知孩子B,让孩子B玩,自己在等待,如此下去,不就实现了轮流的概念了。

上面是理论,实践就可以使用 object的wait和notify去实现。