# 執行緒生命週期

既然是有多個執行緒在執行，管理每個執行緒的工作相當的重要。\
管理好也可以增加執行效率；如哪些執行緒該先睡(sleep) 哪些該暫緩 等等..

而每個執行緒都有他們的生命週期：

## 關係圖

![](/files/-MPaNPw7x-HTxl4H2SzI)

## 生命週期五狀態

* 新產生的 newly created<br>

  > 使用new Thread() 建立物件時，就會進入此狀態。（此時系統不會配置資源）
* 可執行的 runable<br>

  > 當 start() 啟動執行緒，最先搶到資源的先執行 run()；未搶到的將會在 queue 佇列中等待爭取。
* 執行中的 running<br>

  > 先搶到資源的執行緒就會進入這個狀態。（一次僅有一個執行緒會在此狀態）
* 被凍結的 blocked<br>

  > 以下另外討論
* 銷毀的 dead<br>

  > 當 run() 結束，或呼叫 stop() 時就會進入此狀態。（進入此狀態就無法再次啟動）

### 被凍結

被凍結的狀態 我們另外在此討論：碰到以下三點時，就會進入凍結狀態。

1. 呼叫 wait()
2. 呼叫 sleep()
3. 與另一個執行緒 join() 一起時：當有其他執行緒呼叫 join()，原來正執行的執行緒（或程式碼）會先暫停

那麼當執行緒被凍結，就會停止 run() 的執行，等到凍結的因素消失就會回到可執行狀態（排隊搶資源）。\
以下是凍結消失的因素：

* 若執行緒是因為呼叫物件 wait() 而凍結，當物件的 notify() 被呼叫時就可以解凍結。
* 進入睡眠 sleep 狀態，而指定時間已到。

## 附註

sleep() 函數，可用來設定睡眠時間，即 sleep(long millis)。\
毫秒（千分之一秒）。

notify 有「告知」之意。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://java.4-x.tw/java-15/java-15-4.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
