溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java中線程及線程狀態(tài)是什么意思

發(fā)布時(shí)間:2021-07-06 18:02:31 來(lái)源:億速云 閱讀:196 作者:chen 欄目:大數(shù)據(jù)

本篇內(nèi)容主要講解“Java中線程及線程狀態(tài)是什么意思”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“Java中線程及線程狀態(tài)是什么意思”吧!

線程

線程(英語(yǔ):thread)是操作系統(tǒng)能夠進(jìn)行運(yùn)算調(diào)度的最小單位。它被包含在進(jìn)程之中,是進(jìn)程中的實(shí)際運(yùn)作單位。一條線程指的是進(jìn)程中一個(gè)單一順序的控制流,
一個(gè)進(jìn)程中可以并發(fā)多個(gè)線程,每條線程并行執(zhí)行不同的任務(wù)。在Unix System V及SunOS中也被稱為輕量進(jìn)程(lightweight processes),
但輕量進(jìn)程更多指內(nèi)核線程(kernel thread),而把用戶線程(user thread)稱為線程。

以上拷貝自維基百科

代碼中任務(wù)、邏輯操作都依賴于線程,是java運(yùn)行時(shí)最寶貴的資源

多線程一定程度可以增加cpu使用時(shí)間,壓榨計(jì)算機(jī)資源提供更好的使用性能,一定程度也增加了資源的消耗如內(nèi)存的增長(zhǎng)、線程上下文數(shù)據(jù)切換的消耗、cup資源消耗,實(shí)際情況中我們應(yīng)該根據(jù)業(yè)務(wù)場(chǎng)景合理的使用線程資源

Java線程生命周期

Java中線程及線程狀態(tài)是什么意思 ![image-20190712155311451](/Users/yugj/Library/Application Support/typora-user-images/image-20190712155311451.png)

https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/contribute.geeksforgeeks.org/wp-content/uploads/threadLifeCycle.jpg

java.lang.Thread.State 定義了如下6種線程狀態(tài)

/**
 * 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;
  1. New:剛創(chuàng)建,可被執(zhí)行,并且未開(kāi)始執(zhí)行

  2. Runnable:正在執(zhí)行或隨時(shí)準(zhǔn)備執(zhí)行,例如多線程程序分配特定時(shí)間片給特定線程,特定線程執(zhí)行短暫時(shí)間并暫停放棄cpu時(shí)間給其他線程,其他線程因此可以執(zhí)行,這種場(chǎng)景線程是準(zhǔn)備執(zhí)行等待CPU時(shí)間,這種狀態(tài)即Runnable

  3. Blocked:waiting for a monitor lock,處于需要獲取其他線程鎖定的同步資源,如等待io結(jié)束,這種狀態(tài)在轉(zhuǎn)變?yōu)镽unnable之前無(wú)法執(zhí)行,無(wú)法消耗cup時(shí)間片

  4. Waiting:等待其他線程執(zhí)行特定操作,和Blocked類似

  5. Timed Waiting:線程調(diào)用等待執(zhí)行場(chǎng)景,特定時(shí)間后執(zhí)行,比較sleep,或者一些條件等待場(chǎng)景,如定時(shí)任務(wù)

  6. Terminated:正?;虍惓=Y(jié)束線程,將不分配CPU時(shí)間

模擬線程生命周期

1線程狀態(tài)轉(zhuǎn)換

public class DemonstrateThreadStates2 {

    static Thread thread1;

    public static void main(String[] args) {

        //創(chuàng)建線程1
        thread1 = new Thread(new TestThread1());

        // thread1 創(chuàng)建后 NEW state.
        System.out.println("State of thread1 after creating it - ">

控制臺(tái)輸出:

State of thread1 after creating it - NEW
State of thread1 after calling .start() method on it - RUNNABLE
State of thread2 after creating it - NEW
State of thread2 after calling .start() method on it - RUNNABLE
State of thread2 after calling .sleep() method on it - TIMED_WAITING
State of thread1 while it called join() method on thread2 -WAITING
State of thread2 when it has finished it's execution - TERMINATED

線程創(chuàng)建線程變成NEW狀態(tài),調(diào)用start啟動(dòng)線程變成Runnable,調(diào)用sleep阻塞當(dāng)前線程吧變成Timed Waiting,thread2調(diào)用join將等待結(jié)束當(dāng)前線程到父線程thread1,thread2線程將變成die,父線程thread1 等待線程thread2結(jié)束變成waiting

2模擬blocked場(chǎng)景

通過(guò)死鎖模擬blocked場(chǎng)景

死鎖條件

互斥使用:一個(gè)資源只能分配給一個(gè)線程

不可剝奪:資源只能由占有者釋放,申請(qǐng)者不能強(qiáng)制剝奪

請(qǐng)求保持:線程申請(qǐng)資源時(shí),保持對(duì)原有資源的占有

循環(huán)等待:存在一個(gè)進(jìn)程等待隊(duì)列:{P1 , P2 , … , Pn}, 其中P1等待P2占有的資源,P2等待P3占有的資源,…,Pn等待P1占有的資源,形成一個(gè)進(jìn)程等待環(huán)路
代碼
public class TestDeadLock implements Runnable {

    // flag=1,占有對(duì)象o1,等待對(duì)象o2
    // flag=0,占有對(duì)象o2,等待對(duì)象o1
    public int flag = 1;

    // 定義兩個(gè)Object對(duì)象,模擬兩個(gè)線程占有的資源
    public static Object o1 = new Object();
    public static Object o2 = new Object();

    public static void main(String[] args) {

        TestDeadLock deadLock1 = new TestDeadLock();
        TestDeadLock deadLock2 = new TestDeadLock();

        deadLock1.flag = 0;
        deadLock2.flag = 1;

        Thread thread1 = new Thread(deadLock1);
        Thread thread2 = new Thread(deadLock2);

        thread1.start();
        thread2.start();

    }

    @Override
    public void run() {

        System.out.println("flag: " + flag);

        // deadLock2占用資源o1,準(zhǔn)備獲取資源o2
        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("1");
                }
            }
        }

        // deadLock1占用資源o2,準(zhǔn)備獲取資源o1
        else if (flag == 0) {
            synchronized (o2) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("0");
                }
            }
        }
    }

}

參考文獻(xiàn)

https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/

https://www.jianshu.com/p/8cf78bf94f9d

到此,相信大家對(duì)“Java中線程及線程狀態(tài)是什么意思”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI