java Thread 和Runnable區別

來源:互聯網
上載者:User

類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方法,這隻是調用一個方法而已,程式中依然只有主線程--這一個線程,其程式執行路徑還是只有一條,這樣就沒有達到寫線程的目的。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.