Java運行狀態分析1:線程及線程狀態

線程

線程(英語:thread)是操做系統可以進行運算調度的最小單位。它被包含在進程之中,是進程中的實際運做單位。一條線程指的是進程中一個單一順序的控制流,
一個進程中能夠併發多個線程,每條線程並行執行不一樣的任務。在Unix System V及SunOS中也被稱爲輕量進程(lightweight processes),
但輕量進程更多指內核線程(kernel thread),而把用戶線程(user thread)稱爲線程。

以上拷貝自維基百科java

代碼中任務、邏輯操做都依賴於線程,是java運行時最寶貴的資源多線程

多線程必定程度能夠增長cpu使用時間,壓榨計算機資源提供更好的使用性能,必定程度也增長了資源的消耗如內存的增加、線程上下文數據切換的消耗、cup資源消耗,實際狀況中咱們應該根據業務場景合理的使用線程資源併發

Java線程生命週期

![image-20190712155311451](/Users/yugj/Library/Application Support/typora-user-images/image-20190712155311451.png)ide

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種線程狀態spa

/**
 * 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:剛建立,可被執行,而且未開始執行
  2. Runnable:正在執行或隨時準備執行,例如多線程程序分配特定時間片給特定線程,特定線程執行短暫時間並暫停放棄cpu時間給其餘線程,其餘線程所以能夠執行,這種場景線程是準備執行等待CPU時間,這種狀態即Runnable
  3. Blocked:waiting for a monitor lock,處於須要獲取其餘線程鎖定的同步資源,如等待io結束,這種狀態在轉變爲Runnable以前沒法執行,沒法消耗cup時間片
  4. Waiting:等待其餘線程執行特定操做,和Blocked相似
  5. Timed Waiting:線程調用等待執行場景,特定時間後執行,比較sleep,或者一些條件等待場景,如定時任務
  6. Terminated:正常或異常結束線程,將不分配CPU時間

模擬線程生命週期

1線程狀態轉換操作系統

public class DemonstrateThreadStates2 {

    static Thread thread1;

    public static void main(String[] args) {

        //建立線程1
        thread1 = new Thread(new TestThread1());

        // thread1 建立後 NEW state.
        System.out.println("State of thread1 after creating it - " + thread1.getState());
        thread1.start();

        // thread1 調用start後 變成 Runnable state
        System.out.println("State of thread1 after calling .start() method on it - " +
                thread1.getState());

    }

}

class TestThread1 implements Runnable {

    @Override
    public void run() {

        TestThread2 myThread = new TestThread2();
        Thread thread2 = new Thread(myThread);

        // 線程2建立 NEW state.
        System.out.println("State of thread2 after creating it - " + thread2.getState());
        thread2.start();

        // 線程2調用start 變成 Runnable state
        System.out.println("State of thread2 after calling .start() method on it - " +
                thread2.getState());

        // 調用sleep迫使當前線程進入sleep thread2 = timed waiting state
        try {
            //moving thread2 to timed waiting state
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("State of thread2 after calling .sleep() method on it - " +
                thread2.getState());

        try {
            // 調用join迫使線程結束到die
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("State of thread2 when it has finished it's execution - " +
                thread2.getState());
    }
}


class TestThread2 implements Runnable {

    @Override
    public void run() {
        // moving thread2 to timed waiting state
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("State of thread1 while it called join() method on thread2 -" +
                DemonstrateThreadStates2.thread1.getState());
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

控制檯輸出:線程

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

線程建立線程變成NEW狀態,調用start啓動線程變成Runnable,調用sleep阻塞當前線程吧變成Timed Waiting,thread2調用join將等待結束當前線程到父線程thread1,thread2線程將變成die,父線程thread1 等待線程thread2結束變成waitingcode

2模擬blocked場景orm

經過死鎖模擬blocked場景

死鎖條件

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

不可剝奪:資源只能由佔有者釋放,申請者不能強制剝奪

請求保持:線程申請資源時,保持對原有資源的佔有

循環等待:存在一個進程等待隊列:{P1 , P2 , … , Pn}, 其中P1等待P2佔有的資源,P2等待P3佔有的資源,…,Pn等待P1佔有的資源,造成一個進程等待環路
代碼
public class TestDeadLock implements Runnable {

    // flag=1,佔有對象o1,等待對象o2
    // flag=0,佔有對象o2,等待對象o1
    public int flag = 1;

    // 定義兩個Object對象,模擬兩個線程佔有的資源
    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,準備獲取資源o2
        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("1");
                }
            }
        }

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

}

參考文獻

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

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

相關文章
相關標籤/搜索