实现Java多线程
1. 實現Java多線程
有三種使用線程的方法:
- 實現 Runnable 接口;
- 實現 Callable 接口;
- 繼承 Thread 類。
實現 Runnable 和 Callable 接口的類只能當做一個可以在線程中運行的任務,不是真正意義上的線程,因此最后還需要通過 Thread 來調用。可以說任務是通過線程驅動從而執行的。
1.1 繼承Thread類,重寫run()方法;
class MyThread extends Thread{public void run(){System.out.println("Thread body");} }public class Test{public static void main(String[] args){MyThread thread=new MyThread();thread.start();} }1.2 實現Runnable接口,并實現該接口的run()方法;
推薦這個!!(實現這個接口的類還可以繼承自其它的類,用3.1就沒有辦法再去繼承別的類)
Step1:自定義類并實現Rubbale接口,實現run()方法;
Step2:創建Thread對象,用實現Runnable接口的對象作為參數實例化Thread對象;
Step3:調用Thread的start()方法。
class MyThread implements Runnable{public void run(){System.out.println("Thread body");} }public class Test{pulic static void main(String[] args){MyThread thread=new MyThread();Thread t=new Thread(thread);t.start();} }1.3 實現Callable接口,重寫call()方法。
Callable接口實際上是屬于Executor框架中的功能類.
Callable接口與Runnable接口的功能類似,提供了比Runnable更強大的功能,主要表現有三點:
運行結果:
以上三種執行方式,前兩種執行完后都沒有返回值,最后一種帶返回值。
當實現多線程時,一般推薦實現Runnable接口。
一個類是否可以同時繼承Thread與實現Runnable?
可以。
public class Test extends Thread implements Runnable{public static void main(String[] args){Thread t=new Thread();t.start();} }其中,Test類從Thread類繼承的run()被認為是對Runnable接口中run()的實現。
1.4?三種實現方式的比較
- 實現Runnable接口:
- 可以避免Java單繼承特性而帶來的局限;
- 增強程序的健壯性,代碼能夠被多個線程共享,代碼與數據是獨立的;
- 適合多個相同程序代碼的線程區處理同一資源的情況。
- 繼承Thread類和實現Runnable方法啟動線程都是使用start方法,然后JVM虛擬機將此線程放到就緒隊列中,如果有處理機可用, 則執行run方法。
- 實現Callable接口要實現call方法,并且線程執行完畢后會有返回值。其他的兩種都是重寫run方法,沒有返回值。
總結
- 上一篇: 线程安全的实现方法
- 下一篇: MySQL索引(B+Tree 索引、哈希