類A
public class A extends Thread {<br />private Runnable B;<br />@Override<br />public void run() {<br />// TODO Auto-generated method stub<br />super.run();<br />synchronized (this) {<br />B.run();<br />for (int i = 0; i < 10; i++) {<br />System.out.println("the i is/t" + i);<br />}<br />}<br />for (int j = 0; j < 10; j++) {<br />System.out.println("the j is/t" + j);<br />}<br />}<br />//<br />public void getEvent(Runnable B) {<br />synchronized (this) {<br />this.B = B;<br />}<br />}<br />}<br />
類B
public class B implements Runnable {<br />@Override<br />public void run() {<br />// TODO Auto-generated method stub<br />for (int j = 0; j < 10; j++) {<br />System.out.println("the m is/t" + j);<br />}<br />}<br />}
B b=new B();<br />A a=new A();<br />a.getEvent(b);<br />a.start();
結果是如下:
the m is0<br />the m is1<br />the m is2<br />the m is3<br />the m is4<br />the m is5<br />the m is6<br />the m is7<br />the m is8<br />the m is9<br />the i is0<br />the i is1<br />the i is2<br />the i is3<br />the i is4<br />the i is5<br />the i is6<br />the i is7<br />the i is8<br />the i is9<br />the j is0<br />the j is1<br />the j is2<br />the j is3<br />the j is4<br />the j is5<br />the j is6<br />the j is7<br />the j is8<br />the j is9<br />
B變成Thread
public class B extends Thread {<br />@Override<br />public void run() {<br />// TODO Auto-generated method stub<br />for (int j = 0; j < 10; j++) {<br />System.out.println("the m is/t" + j);<br />}<br />}<br />}
把A中 B.run-->B.start();
得到的結果就m的位置是隨機。。。。
the i is0<br />the i is1<br />the i is2<br />the i is3<br />the i is4<br />the i is5<br />the i is6<br />the m is0<br />the m is1<br />the m is2<br />the m is3<br />the m is4<br />the m is5<br />the m is6<br />the m is7<br />the m is8<br />the m is9<br />the i is7<br />the i is8<br />the i is9<br />the j is0<br />the j is1<br />the j is2<br />the j is3<br />the j is4<br />the j is5<br />the j is6<br />the j is7<br />the j is8<br />the j is9
問題:Runnable和Thread實現的有何區別?A.run()和A.start()區別??
通過調用Thread類的start()方法來啟動一個線程,這時此線程是處於就緒狀態,並沒有運行。然後通過此Thread類調用方法run()來完成其運行操作的,這裡方法run()稱為線程體,它包含了要執行的這個線程的內容,Run方法運行結束,此線程終止,而CPU再運行其它線程,而如果直接用Run方法,這隻是調用一個方法而已,程式中依然只有主線程--這一個線程,其程式執行路徑還是只有一條,這樣就沒有達到寫線程的目的。