Java基礎之執行緒Thread
在程式開發中, 一定遇到併發程式設計的場景, 雖然我們大部分時間並不直接使用Thread, 但是Thread是多執行緒的基礎, 面試中也會總是被問到與執行緒有關的問題; 那麼執行緒都有哪些知識呢? 最近在研究執行緒的原始碼的時候也總結了關於執行緒一些基本知識;
執行緒是什麼
執行緒是輕量級的程序, 是作業系統排程任務到CPU的最小單元;
多執行緒程式設計的優點
1、多執行緒程式設計能夠最大程度的利用多核裝置上面的CPU資源, 保證任務處理的足夠快, 及時響應客戶端的額請求
2、執行緒的建立的代價比建立程序的代價小很多, 同時多執行緒的上下文切換也更快; 《作業系統概念 第六版》 在Solaris 2上面, 建立程序比建立執行緒慢30倍, 而程序的上下文切換比執行緒的上下文切換慢5倍;
Java中執行緒的狀態有哪些
檢視java.lang.Thread的原始碼有如下程式碼:
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; }
1、NEW: 執行緒還沒有啟動的時候, 狀態就是 NEW
即 新建狀態
2、RUNNABLE: 當一個執行緒處於執行中或者等待CPU排程的時候, 狀態就是 RUNNABLE
狀態; 有些地方也稱為 就緒狀態
3、BLOCKED: 當一個執行緒在等待別的執行緒釋放鎖資源的時候, 狀態就是 BLOCKED
, 或者在該執行緒獲取到鎖之後, 在同步程式碼塊裡面呼叫了Wait方法, 這時候釋放鎖, 在獲取到其他執行緒的notify或者notifyAll通知之後, 重新進入 同步程式碼塊這段時間 該執行緒也是 BLOCKED
狀態的;
4、WAITING: 當正在執行的執行緒呼叫了 Object.wait()
方法 或者 Thread.join()
方法 或者 LockSupport.park()
方法之後, 會進入到 WAITING
狀態
5、TIMED_WAITING: 當正在執行的執行緒呼叫 Object.wait(n)
或者 Thread.join(n)
或者 LockSupport.parkUntil(blocker, n)
會進入到 TIMED_WAITING
狀態
6、TERMINATED: 當執行緒結束後, 會進入到 TERMINATED
狀態.
狀態轉換如下, 該圖中比Java的狀態多了一個RUNNING狀態, 來區別 執行緒的就緒狀態 與 執行狀態 更加方便讀者理解;
下面來看一下執行緒的狀態轉換用Java怎麼實現: