Java Thread你應(yīng)該知道的一切

線程的知識點真的很多,想要全面掌握昂拂,需要日積月累,今天就請大家跟隨我枕面,一起走進(jìn)Thread的世界愿卒。
想要走進(jìn)Thread,那么就從源碼開始吧缚去。

Thead State 線程的狀態(tài)

這個知識點潮秘,是你必須知道的,線程那些狀態(tài)呢易结?

public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

上面的枚舉類是Thread內(nèi)部枚舉枕荞,里面包含了線程的幾種狀態(tài),那么我們來看看搞动,都是什么狀態(tài)躏精。

NEW

Thread state for a thread which has not yet started

public class ThreadTest {
    public static void main(String[] args){
        Thread thread = new Thread();
        Thread.State state = thread.getState();
        System.out.println(state.toString());
    }
}

當(dāng)運行以上代碼的時候,打印結(jié)果是 NEW鹦肿,這樣我們可以理解矗烛,線程創(chuàng)建以后,在沒有調(diào)用start方法以前箩溃,Thread的狀態(tài)是NEW.

RUNNABLE

Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.

public class ThreadTest {
    public static void main(String[] args){
        Thread thread = new Thread();
        thread.start();
        Thread.State state = thread.getState();
        System.out.println(state.toString());
    }
}

當(dāng)運行以上代碼的時候瞭吃,打印的結(jié)果是RUNNABLE,當(dāng)前線程從NEW狀態(tài)轉(zhuǎn)到了RUNNABLE狀態(tài)涣旨。
在網(wǎng)上看到好多人在寫Thread狀態(tài)的時候歪架,還有運行中狀態(tài),這是不正確的霹陡,如何用代碼證明呢和蚪?

public class ThreadTest {
    public static void main(String[] args){
        Thread thread = new Thread(new MyThread());
        thread.start();

        Thread.State state = thread.getState();
        System.out.println(state.toString());
    }

    static class MyThread implements Runnable{

        public void run() {
            int count = 0;
            for (int i=0;i<10000;i++){
                count = count+i;
                System.out.println(Thread.currentThread().getState().toString());
            }
        }
    }
}

運行以上代碼,你會發(fā)現(xiàn)烹棉,線程根本沒有所謂的運行中的狀態(tài)攒霹,CPU已經(jīng)計算結(jié)果了

BLOCKED

Thread state for a thread blocked waiting for a monitor lock.
A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling {@link Object#wait() Object.wait}
阻塞狀態(tài),當(dāng)前線程在等待一個monitor lock。
1.調(diào)用synchronized浆洗,使線程進(jìn)入阻塞狀態(tài)催束。
2.調(diào)用wait方法,使線程進(jìn)入阻塞狀態(tài)辅髓。

WAITING

使線程進(jìn)入WAITING狀態(tài)的幾種場景:
1.調(diào)用了wait方法泣崩,沒有設(shè)置過期時間
2.調(diào)用Thread.join方法,沒有設(shè)置過期時間
3.調(diào)用了LockSupport#park

TIMED_WAITING

使線程進(jìn)入TIMED_WAITING狀態(tài)的幾種場景:
1.調(diào)用了Thread.sleep方法
2.調(diào)用了Object.wati方法洛口,設(shè)置了過期時間
3.調(diào)用了Thread.join方法矫付,設(shè)置了過期時間
4.調(diào)用了LockSupport#parkNanos
5.調(diào)用了LockSupport#parkUntil

TERMINATED

線程已經(jīng)執(zhí)行完成,就進(jìn)入了線程終止?fàn)顟B(tài)第焰。

線程的優(yōu)先級

當(dāng)多個線程的優(yōu)先級相同的時候买优,它們使搶奪CPU資源。如果,你想讓某個線程有限執(zhí)行杀赢,你就可以設(shè)置它的優(yōu)先級烘跺,可以通過Thread.setPriority設(shè)置線程優(yōu)先級,優(yōu)先級一共有10個級別脂崔,線程默認(rèn)的優(yōu)先級使5

/**
  * 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;
public final void setPriority(int newPriority) {
      ThreadGroup g;
        checkAccess();
        if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
            throw new IllegalArgumentException();
        }
        if((g = getThreadGroup()) != null) {
            if (newPriority > g.getMaxPriority()) {
                newPriority = g.getMaxPriority();
            }
            setPriority0(priority = newPriority);
        }
    }

守護(hù)線程

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末滤淳,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子砌左,更是在濱河造成了極大的恐慌脖咐,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件汇歹,死亡現(xiàn)場離奇詭異屁擅,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)产弹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進(jìn)店門派歌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人痰哨,你說我怎么就攤上這事胶果。” “怎么了作谭?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵稽物,是天一觀的道長。 經(jīng)常有香客問我折欠,道長贝或,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任锐秦,我火速辦了婚禮咪奖,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘酱床。我一直安慰自己羊赵,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布扇谣。 她就那樣靜靜地躺著昧捷,像睡著了一般。 火紅的嫁衣襯著肌膚如雪罐寨。 梳的紋絲不亂的頭發(fā)上靡挥,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天,我揣著相機(jī)與錄音鸯绿,去河邊找鬼跋破。 笑死簸淀,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的毒返。 我是一名探鬼主播租幕,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼拧簸!你這毒婦竟也來了劲绪?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤狡恬,失蹤者是張志新(化名)和其女友劉穎珠叔,沒想到半個月后蝎宇,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體弟劲,經(jīng)...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年姥芥,在試婚紗的時候發(fā)現(xiàn)自己被綠了兔乞。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡凉唐,死狀恐怖庸追,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情台囱,我是刑警寧澤淡溯,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站簿训,受9級特大地震影響咱娶,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜强品,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一膘侮、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧的榛,春花似錦琼了、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至晓淀,卻和暖如春所袁,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背要糊。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工纲熏, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留妆丘,地道東北人。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓局劲,卻偏偏與公主長得像勺拣,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子鱼填,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,092評論 2 355

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

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法药有,類相關(guān)的語法,內(nèi)部類的語法苹丸,繼承相關(guān)的語法愤惰,異常的語法,線程的語...
    子非魚_t_閱讀 31,644評論 18 399
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理赘理,服務(wù)發(fā)現(xiàn)宦言,斷路器,智...
    卡卡羅2017閱讀 134,672評論 18 139
  • Lua 5.1 參考手冊 by Roberto Ierusalimschy, Luiz Henrique de F...
    蘇黎九歌閱讀 13,813評論 0 38
  • Java多線程學(xué)習(xí) [-] 一擴(kuò)展javalangThread類 二實現(xiàn)javalangRunnable接口 三T...
    影馳閱讀 2,959評論 1 18
  • 白駒過隙响疚,星移斗轉(zhuǎn)。 歲月的老墻剝落了時光的痕跡瞪醋。 風(fēng)刮進(jìn)小屋忿晕, 將書桌上的日歷翻向最后一頁。 鐘聲順著新年的腳步...
    豪司令閱讀 338評論 0 2