詳解三種java實現多線程的方式_java

來源:互聯網
上載者:User

java中實現多線程的方法有兩種:繼承Thread類和實現runnable介面

1.繼承Thread類,重寫父類run()方法

 public class thread1 extends Thread {     public void run() {        for (int i = 0; i < 10000; i++) {            System.out.println("我是線程"+this.getId());        }    }     public static void main(String[] args) {        thread1 th1 = new thread1();        thread1 th2 = new thread1();        th1.run();        th2.run();    }   }

run()方法只是普通的方法,是順序執行的,即th1.run()執行完成後才執行th2.run(),這樣寫只用一個主線程。多線程就失去了意義,所以應該用start()方法來啟動線程,start()方法會自動調用run()方法。上述代碼改為:

 public class thread1 extends Thread {         public void run() {        for (int i = 0; i < 10000; i++) {            System.out.println("我是線程"+this.getId());        }    }     public static void main(String[] args) {        thread1 th1 = new thread1();        thread1 th2 = new thread1();        th1.start();        th2.start();    }}

通過start()方法啟動一個新的線程。這樣不管th1.start()調用的run()方法是否執行完,都繼續執行th2.start()如果下面有別的代碼也同樣不需要等待th2.start()執行完成,而繼續執行。(輸出的線程id是無規則交替輸出的)

2.實現runnable介面

public class thread2 implements Runnable {     public String ThreadName;         public thread2(String tName){        ThreadName = tName;    }              public void run() {        for (int i = 0; i < 10000; i++) {            System.out.println(ThreadName);        }    }         public static void main(String[] args) {        thread2 th1 = new thread2("線程A");        thread2 th2 = new thread2("線程B");        th1.run();        th2.run();    }}

和Thread的run方法一樣Runnable的run只是普通方法,在main方法中th2.run()必須等待th1.run()執行完成後才能執行,程式只用一個線程。要多線程的目的,也要通過Thread的start()方法(注:runnable是沒有start方法)。上述代碼修改為:

public class thread2 implements Runnable {     public String ThreadName;         public thread2(String tName){        ThreadName = tName;    }              public void run() {        for (int i = 0; i < 10000; i++) {            System.out.println(ThreadName);        }    }         public static void main(String[] args) {        thread2 th1 = new thread2("線程A");        thread2 th2 = new thread2("Thread-B");        Thread myth1 = new Thread(th1);        Thread myth2 = new Thread(th2);        myth1.start();        myth2.start();    }}

3.使用ExecutorService、Callable、Future實現有返回結果的多線程(JDK5.0以後)
可傳回值的任務必須實現Callable介面,類似的,無傳回值的任務必須Runnable介面。執行Callable任務後,可以擷取一個Future的對象,在該對象上調用get就可以擷取到Callable任務返回的Object了,再結合線程池介面ExecutorService就可以實現傳說中有返回結果的多線程了。下面提供了一個完整的有返回結果的多線程測試例子,在JDK1.5下驗證過沒問題可以直接使用。代碼如下:

import java.util.concurrent.*; import java.util.Date; import java.util.List; import java.util.ArrayList;   /** * 有傳回值的線程 */ @SuppressWarnings("unchecked") public class Test { public static void main(String[] args) throws ExecutionException,   InterruptedException {   System.out.println("----程式開始運行----");   Date date1 = new Date();     int taskSize = 5;   // 建立一個線程池   ExecutorService pool = Executors.newFixedThreadPool(taskSize);   // 建立多個有傳回值的任務   List<Future> list = new ArrayList<Future>();   for (int i = 0; i < taskSize; i++) {   Callable c = new MyCallable(i + " ");   // 執行任務並擷取Future對象   Future f = pool.submit(c);   // System.out.println(">>>" + f.get().toString());   list.add(f);   }   // 關閉線程池   pool.shutdown();     // 擷取所有並發任務的運行結果   for (Future f : list) {   // 從Future對象上擷取任務的傳回值,並輸出到控制台   System.out.println(">>>" + f.get().toString());   }     Date date2 = new Date();   System.out.println("----程式結束運行----,程式已耗用時間【"    + (date2.getTime() - date1.getTime()) + "毫秒】"); } }   class MyCallable implements Callable<Object> { private String taskNum;   MyCallable(String taskNum) {   this.taskNum = taskNum; }   public Object call() throws Exception {   System.out.println(">>>" + taskNum + "任務啟動");   Date dateTmp1 = new Date();   Thread.sleep(1000);   Date dateTmp2 = new Date();   long time = dateTmp2.getTime() - dateTmp1.getTime();   System.out.println(">>>" + taskNum + "任務終止");   return taskNum + "任務返回運行結果,當前任務時間【" + time + "毫秒】"; } }

代碼說明:
上述代碼中Executors類,提供了一系列Factory 方法用於創先線程池,返回的線程池都實現了ExecutorService介面。
public static ExecutorService newFixedThreadPool(int nThreads)
建立固定數目線程的線程池。
public static ExecutorService newCachedThreadPool()
建立一個可快取的線程池,調用execute 將重用以前構造的線程(如果線程可用)。如果現有線程沒有可用的,則建立一個新線程並添加到池中。終止並從緩衝中移除那些已有 60 秒鐘未被使用的線程。
public static ExecutorService newSingleThreadExecutor()
建立一個單線程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
建立一個支援定時及周期性的任務執行的線程池,多數情況下可用來替代Timer類。
ExecutoreService提供了submit()方法,傳遞一個Callable,或Runnable,返回Future。如果Executor後台線程池還沒有完成Callable的計算,這調用返回Future對象的get()方法,會阻塞直到計算完成。

總結:實現java多線程的2種方式,runable是介面,thread是類,runnable只提供一個run方法,建議使用runable實現 java多線程,不管如何,最終都需要通過thread.start()來使線程處於可運行狀態。第三種方法是聽群裡的兄弟們介紹的,所以就百度補上了。

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

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