Java线程 Thread 的6种状态以及转变过程
線程的6種狀態以及轉變:
java的線程一共6種狀態。具體代碼見:
java.lang.Thread.State1 NEW
新建狀態
Thread state for a thread which has not yet started.
線程還沒有調用start的時候
2 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.
調用start之后,jvm啟動了這個任務,但是可能被其他資源占用線程變成WAITING
3 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}.
線程被鎖的時候,線程等待進去一個synchronized塊方法或者可重入鎖的時候
4 WAITING
等待狀態
Thread state for a waiting thread.
A thread is in the waiting state due to calling one of the
following methods:
- {@link Object#wait() Object.wait} with no timeout< li>
- {@link #join() Thread.join} with no timeout< li>
- {@link LockSupport#park() LockSupport.park}< li>
< ul>
A thread in the waiting state is waiting for another thread to
perform a particular action.
For example, a thread that has called Object.wait()
on an object is waiting for another thread to call
Object.notify() or Object.notifyAll() on
that object A thread that has called Thread.join()線程調用object.wait thread.join LockSupport.park 的時候變成 WAITING
5 TIMED_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:
- {@link #sleep Thread.sleep}< li>
- {@link Object#wait(long) Object.wait} with timeout< li>
- {@link #join(long) Thread.join} with timeout< li>
- {@link LockSupport#parkNanos LockSupport.parkNanos}< li>
- {@link LockSupport#parkUntil LockSupport.parkUntil}< li>
< ul>
sleep 或者wait,join帶時間參數等方法時
6 TERMINATED
終止狀態
Thread state for a terminated thread.
The thread has completed execution.
線程執行完成 或者被中斷的時候變成TERMINATED
TERMINATED;
狀態流轉圖
線程創建出來就是new的狀態。
start方法調用之后狀態變成runnable,可以執行,如果cpu把時間片切過來就可以執行。
runnable執行完成則變成terminated,或者中斷的時候。
runnable如果遇到有鎖的方法,在等待的時候則是阻塞blocked的狀態
如果調用wait或者join的方法,則變成waiting狀態,
如果調用帶時間參數的wait或者join,則變成time_waiting。
總結
以上是生活随笔為你收集整理的Java线程 Thread 的6种状态以及转变过程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 源码学习【HashMap第二篇】hash
- 下一篇: 看了这一篇,就不用看别的——Java中O