Java有兩種方式實現多線程,第一個是繼承Thread類,第二個是實現Runnable介面。他們之間的聯絡:
1、Thread類實現了Runable介面。
2、都需要重寫裡面Run方法。
他們之間的區別“
1、實現Runnable的類更具有健壯性,避免了單繼承的局限。
2、Runnable更容易實現資源共用,能多個線程同時處理一個資源。
看一下以繼承Thread的賣票例子:
public static void main(String[] args) {// TODO Auto-generated method stubnew MyThread().start();new MyThread().start();}class MyThread extends Thread{ private int ticket = 5; public void run(){ while(true){ System.out.println("Thread ticket = " + ticket--); if(ticket < 0){ break; } } } }
輸出結果:
Thread ticket = 5Thread ticket = 5Thread ticket = 4Thread ticket = 4Thread ticket = 3Thread ticket = 2Thread ticket = 3Thread ticket = 1Thread ticket = 2Thread ticket = 0Thread ticket = 1Thread ticket = 0
從以上輸出結果可以看出,我們創造了2個多線程對象,他們分別實現了買票任務,也就是一共賣了12張票。
實現Runnable介面的賣票例子:
<pre name="code" class="html">public static void main(String[] args) {// TODO Auto-generated method stubMyThread2 m=new MyThread2();new Thread(m).start();new Thread(m).start();}class MyThread2 implements Runnable{ private int ticket = 5; public void run(){ while(true){ System.out.println("Runnable ticket = " + ticket--); if(ticket < 0){ break; } } } } 輸出結果:
Runnable ticket = 5Runnable ticket = 4Runnable ticket = 3Runnable ticket = 2Runnable ticket = 1Runnable ticket = 0
從結果我們可以看到,雖然我們聲明了兩個線程,但是一共賣了6張票。他們實現了資源共用。PS:在實際開發中,一定要注意命名規範,其次上面實現Runable介面的例子由於同時操作一個資源,會出現線程不安全的情況,如果情況需要,我們需要進行同步操作。