Java併發編程-線程的狀態與相互轉換

概述

解析

根據源碼, 可以看到線程擁有的狀態枚舉.
// java.lang.Thread 1742

 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;
    }

NEW狀態:

Thread t = new Thread();
System.out.println("t.state: " + t.getState());
// t.state: NEW

RUNABLE狀態:

Thread t = new Thread(() -> {
    for (int i = 0; i < 10000; i++) {
        System.out.println(i);
    }
});
t.start();
System.out.println("t.state: " + t.getState());
// t.state: RUNNABLE

BLOCKED狀態:

public class ThreadStateStarter {
    private static synchronized void func() {
        for (int i = 0; i < 1000; i++) {
            System.out.print("");
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(ThreadStateStarter::func);
        Thread t2 = new Thread(ThreadStateStarter::func);
        t1.start();
        t2.start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("t1.state: " + t1.getState());
            System.out.println("t2.state: " + t2.getState());
        }
    }
}
// t1或者t2會被阻塞在鎖上, 狀態爲BLOCKED

WAITING狀態:

Object lock = new Object();
Thread t = new Thread(() -> {
    System.out.print("");
    try {
        synchronized (lock) {
            lock.wait();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});
t.start();
Thread.sleep(200);
System.out.println("t.state: " + t.getState());

JOIN導致的WAITING狀態:

public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(() -> {
        try {
            Thread.sleep(2000);
            System.out.println("t end.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    MyThread mt = new MyThread(t);
    t.start();
    mt.start();
    Thread.sleep(500);
    System.out.println("mt.state: " + mt.getState());
}

static class MyThread extends Thread {
    private Thread joinThread;

    public MyThread(Thread joinThread) {
        this.joinThread = joinThread;
    }

    @Override
    public void run() {
        try {
            // 等待joinThread執行完成之後, 當前線程才繼續執行.
            joinThread.join();
            System.out.println("mt end.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
/*
輸出:
------------------------------
mt.state: WAITING
t end.
mt end.
------------------------------
*/

不同狀態的轉換

線程的停止

有啓動則會有停止, 如何停止一個線程?可以直接關閉電源而粗暴的停止線程, 這會導致數據狀態的不一致性, 所以最好是採用讓線程緩慢執行完所有的過程而停止.
如果一個線程的任務,沒有阻塞,則可能自然而然的結束了. 但是如果線程執行過程中存在sleep,wait, join等情況, 可能會導致線程無法快速結束, 甚至如果存在死鎖, 則永久無法結束等問題.
可以採用interrrupt來中斷線程.

Java線程的中斷機制

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章