Java - 線程 & 線程池

概述:創(chuàng)建線程有兩種方法,一種是繼承Thread類,另一種是實現(xiàn)Runnable接口。

創(chuàng)建線程

創(chuàng)建線程有兩種方法:

  1. 繼承Thread類
  2. 實現(xiàn)Runnable接口

繼承Thread類

public class ExtendThead extends Thread{

    private int no;

    public ExtendThead(int no){
        this.no = no;
    }

    @Override
    public void run(){
        try {
            for(int i = 1; i <6; i++) {
                System.out.println("Child Thread: " + no + "-" + i);
                // 讓線程休眠一會
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            System.out.println("Child interrupted.");
        }
        System.out.println("Exiting child thread.");
    }
}

//==============================
public class MyThread {

    public static void main( String[] args ){

        //注意,使用start()方法,不是run()方法。run()方法并不能啟動新的線程。
        new ExtendThead(1).start();  
        new ExtendThead(2).start();
        new ExtendThead(3).start();
        new ExtendThead(4).start();

        for(int i = 1; i <6; i++) {
            System.out.println("Main Thread: " + i);
            // 讓線程休眠一會
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

實現(xiàn)Runnable接口

public class RunnableThread implements Runnable{

    private int no;

    public RunnableThread(int no){
        this.no = no;
    }

    @Override
    public void run(){
        try {
            for(int i = 1; i <6; i++) {
                System.out.println("Runnable Thread: " + no + "-" + i);
                // 讓線程休眠一會
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            System.out.println("Runnable interrupted.");
        }
        System.out.println("Exiting Runnable thread.");
    }
}

//==============================
public class MyThread {

    public static void main( String[] args ){

        //注意,使用start()方法,不是run()方法。run()方法并不能啟動新的線程。
        new Thread(new RunnableThread(1)).start();
        new Thread(new RunnableThread(2)).start();
        new Thread(new RunnableThread(3)).start();
        new Thread(new RunnableThread(4)).start();

        for(int i = 1; i <6; i++) {
            System.out.println("Main Thread: " + i);
            // 讓線程休眠一會
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

注意:實現(xiàn)Runnable接口的類沒有任何線程能力,只有將其顯示地附著在一個線程上,才會有線程能力。即只能將Runnable類的實例通過參數(shù)傳入Thread類實例來啟動線程:new Thread(Runnable).start()

很多情況下,使用Runnable接口創(chuàng)建線程時,直接使用匿名類的方法創(chuàng)建,會更簡單:

public static void main( String[] args ){

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for(int i = 1; i <6; i++) {
                        System.out.println("Runnable Thread: " + i);
                        // 讓線程休眠一會
                        Thread.sleep(500);
                    }
                } catch (InterruptedException e) {
                    System.out.println("Runnable interrupted.");
                }
            }
        }).start();

    }

Thread 和Runnable的區(qū)別

  • Thread是個class,java中class只能單繼承
  • Runnable是個Interface,擴展性比較好
  • Runnable定義的子類中沒有start()方法,只有Thread類中才有。因此使用Runnable要通過Thread。new Thread(new Runnable)

線程的一些特征

返回值

如果希望任務完成時,返回一個結(jié)果,就不能使用Thread和Runnable。這時需要實現(xiàn)Callable接口,并必須使用ExecutorService.submit()方法來調(diào)用。

Callable定義如下。可以看到Callable接口只有一個call()方法,并且支持返回值。

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

ExecutorService的submit方法:

public interface ExecutorService extends Executor {
    <T> Future<T> submit(Callable<T> task);
}

返回值是一個Future對象。

public interface Future<V> {
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

可以通過調(diào)用Future對象的isDone()方法來查看任務是否已經(jīng)完成。或者使用get()方法來獲取返回結(jié)果。注意,get()會阻塞主線程,直至子線程任務完成。所以一般情況下,在直接調(diào)用get()方法之前,會首先使用isDone()或者帶有超時的get()方法查看任務是否完成。

休眠

讓線程休眠一段時間,方法是Thread.sleep(milliseconds)

線程優(yōu)先級

使用getPriority()方法來獲取線程優(yōu)先級。
使用setPriority()方法來設定線程的優(yōu)先級。

public class Thread implements Runnable {
    **
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;
}

可以看到,JDK定義了10個優(yōu)先級。不過多數(shù)與操作系統(tǒng)映射的不好。比如Windows有7個優(yōu)先級,其映射關(guān)系還不固定。所以,為了方便移植,最好只使用Thread中定義的三種優(yōu)先級。

public class Test implements Runnable{
    public void run(){
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        //do something
    }
}

注意:

  1. 設置線程優(yōu)先級通常在run()方法的開頭設置。
  2. 極其不建議改變線程優(yōu)先級。

Daemon線程

Daemon線程即后臺線程。
與后臺線程對應的是非后臺線程。如主線程是非后臺線程,啟動的默認設置線程也是非后臺線程。
非后臺線程有個特點是:只要有任何一個非后臺線程正在運行,程序就不會終止。
與之對應,后臺線程特點是,當所有非后臺線程結(jié)束時,程序會終止,此時會結(jié)束所有后臺線程。任何一個非后臺線程結(jié)束時,都會殺死該非后臺線程啟動的后臺線程。

設置線程為后臺線程的方法:new Thread().setDaemon(true)

如:

Thread test = new Thread(new Runnable(){
    public void run(){
        //do something
    }
});
test.setDaemon(true);
test.start();

可以通過isDaemon()方法判斷一個線程是否是后臺線程。

主線程等待子線程結(jié)束

使用join

public class MyThread {

    public static void main( String[] args ){

        //注意,使用start()方法,不是run()方法。run()方法并不能啟動新的線程。
        Thread t1 = new Thread(new RunnableThread(1)).start();
        Thread t2 = new Thread(new RunnableThread(2)).start();
        Thread t3 = new Thread(new RunnableThread(3)).start();
        Thread t4 = new Thread(new RunnableThread(4)).start();

        for(int i = 1; i <6; i++) {
            System.out.println("Main Thread: " + i);
            // 讓線程休眠一會
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t1.join();
        t2.join();
        t3.join();
        t4.join();
    }
}

線程池

請見 Java線程池

參考

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,119評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,382評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,038評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,853評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,616評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,112評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,192評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,355評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,869評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,727評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,928評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,467評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,165評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,570評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,813評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,585評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,892評論 2 372

推薦閱讀更多精彩內(nèi)容

  • 進程和線程 進程 所有運行中的任務通常對應一個進程,當一個程序進入內(nèi)存運行時,即變成一個進程.進程是處于運行過程中...
    勝浩_ae28閱讀 5,130評論 0 23
  • 進程和線程 進程 所有運行中的任務通常對應一個進程,當一個程序進入內(nèi)存運行時,即變成一個進程.進程是處于運行過程中...
    小徐andorid閱讀 2,825評論 3 53
  • 一、前言 ??如果我們平時接觸過多線程開發(fā),那肯定對線程池不陌生。在我們原先的學習中,我們了解到,如果我們需要創(chuàng)建...
    騎著烏龜去看海閱讀 436評論 0 4
  • 下面是我自己收集整理的Java線程相關(guān)的面試題,可以用它來好好準備面試。 參考文檔:-《Java核心技術(shù) 卷一》-...
    阿呆變Geek閱讀 14,883評論 14 507
  • 打下這題目,想起上周末陪女兒去圖書館借的那本《沒頭腦和不高興》,是不是很像?內(nèi)心偷笑十秒鐘。。。 言歸正傳。這篇是...
    魚子醬閱讀 1,894評論 0 0