实现Java多线程
1. 實(shí)現(xiàn)Java多線程
有三種使用線程的方法:
- 實(shí)現(xiàn) Runnable 接口;
- 實(shí)現(xiàn) Callable 接口;
- 繼承 Thread 類。
實(shí)現(xiàn) Runnable 和 Callable 接口的類只能當(dāng)做一個(gè)可以在線程中運(yùn)行的任務(wù),不是真正意義上的線程,因此最后還需要通過 Thread 來調(diào)用。可以說任務(wù)是通過線程驅(qū)動(dòng)從而執(zhí)行的。
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 實(shí)現(xiàn)Runnable接口,并實(shí)現(xiàn)該接口的run()方法;
推薦這個(gè)!!(實(shí)現(xiàn)這個(gè)接口的類還可以繼承自其它的類,用3.1就沒有辦法再去繼承別的類)
Step1:自定義類并實(shí)現(xiàn)Rubbale接口,實(shí)現(xiàn)run()方法;
Step2:創(chuàng)建Thread對(duì)象,用實(shí)現(xiàn)Runnable接口的對(duì)象作為參數(shù)實(shí)例化Thread對(duì)象;
Step3:調(diào)用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 實(shí)現(xiàn)Callable接口,重寫call()方法。
Callable接口實(shí)際上是屬于Executor框架中的功能類.
Callable接口與Runnable接口的功能類似,提供了比Runnable更強(qiáng)大的功能,主要表現(xiàn)有三點(diǎn):
運(yùn)行結(jié)果:
以上三種執(zhí)行方式,前兩種執(zhí)行完后都沒有返回值,最后一種帶返回值。
當(dāng)實(shí)現(xiàn)多線程時(shí),一般推薦實(shí)現(xiàn)Runnable接口。
一個(gè)類是否可以同時(shí)繼承Thread與實(shí)現(xiàn)Runnable?
可以。
public class Test extends Thread implements Runnable{public static void main(String[] args){Thread t=new Thread();t.start();} }其中,Test類從Thread類繼承的run()被認(rèn)為是對(duì)Runnable接口中run()的實(shí)現(xiàn)。
1.4?三種實(shí)現(xiàn)方式的比較
- 實(shí)現(xiàn)Runnable接口:
- 可以避免Java單繼承特性而帶來的局限;
- 增強(qiáng)程序的健壯性,代碼能夠被多個(gè)線程共享,代碼與數(shù)據(jù)是獨(dú)立的;
- 適合多個(gè)相同程序代碼的線程區(qū)處理同一資源的情況。
- 繼承Thread類和實(shí)現(xiàn)Runnable方法啟動(dòng)線程都是使用start方法,然后JVM虛擬機(jī)將此線程放到就緒隊(duì)列中,如果有處理機(jī)可用, 則執(zhí)行run方法。
- 實(shí)現(xiàn)Callable接口要實(shí)現(xiàn)call方法,并且線程執(zhí)行完畢后會(huì)有返回值。其他的兩種都是重寫run方法,沒有返回值。
總結(jié)
- 上一篇: 线程安全的实现方法
- 下一篇: Java实现线程同步的方式