java中建立線程的三種方法以及區別

來源:互聯網
上載者:User

標籤:ring   oid   main   public   art   代碼   extends   使用   star   

Java使用Thread類代表線程,所有的線程對象都必須是Thread類或其子類的執行個體。Java可以用三種方式來建立線程,如下所示:

1)繼承Thread類建立線程

2)實現Runnable介面建立線程

3)使用Callable和Future建立線程

下面讓我們分別來看看這三種建立線程的方法。

 

------------------------繼承Thread類建立線程---------------------

 

通過繼承Thread類來建立並啟動多線程的一般步驟如下

1】d定義Thread類的子類,並重寫該類的run()方法,該方法的方法體就是線程需要完成的任務,run()方法也稱為線程執行體。

2】建立Thread子類的執行個體,也就是建立了線程對象

3】啟動線程,即調用線程的start()方法

代碼執行個體

public class MyThread extends Thread{//繼承Thread類

  public void run(){

  //重寫run方法

  }

}

public class Main {

  public static void main(String[] args){

    new MyThread().start();//建立並啟動線程

  }

}

------------------------實現Runnable介面建立線程---------------------

通過實現Runnable介面建立並啟動線程一般步驟如下:

1】定義Runnable介面的實作類別,一樣要重寫run()方法,這個run()方法和Thread中的run()方法一樣是線程的執行體

2】建立Runnable實作類別的執行個體,並用這個執行個體作為Thread的target來建立Thread對象,這個Thread對象才是真正的線程對象

3】第三部依然是通過調用線程對象的start()方法來啟動線程

代碼執行個體:

public class MyThread2 implements Runnable {//實現Runnable介面

  public void run(){

  //重寫run方法

  }

}

public class Main {

  public static void main(String[] args){

    //建立並啟動線程

    MyThread2 myThread=new MyThread2();

    Thread thread=new Thread(myThread);

    thread().start();

    //或者    new Thread(new MyThread2()).start();

  }

}

 

java中建立線程的三種方法以及區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.