# 認識多執行緒

多執行緒可以讓程式不必跟著一定的流程執行，或一次只能執行一個區塊。

Ｑ：那麼執行緒是什麼？\
Ａ：執行緒 （thread） 意指程式的執行流程。

有些迴圈的執行緒需要花較多的時間，此刻我們可以啟動另一個執行緒來執行。

> 多執行緒 （multi-thread）就是可以同時執行多個程式區塊。

讓我們先看看 如果有個空迴圈執行緒較長，的一個不好的範例：

```
class multi_Test
{
   private String name;
   public multi_Test(String str)
   {
      name=str;
   }
   public void show()
   {
      for(int i=0;i<3;i++)
      {
         for(int j=0;j<100000000;j++);
         System.out.println(name);
      }
   }
}

public class multi_thread_1
{
   public static void main(String args[])
   {
      multi_Test apple=new multi_Test("apple");
      multi_Test pen=new multi_Test("pen");
      apple.show();
      pen.show();
   }
}
```

在上方的範例當中，故意加了一行空的迴圈 來拖慢下一行的執行速度

```
for(int j=0;j<100000000;j++);
```

另外，apple.show(); 執行後 才會輪到pen.show();\
這是單一執行緒的限制；如果啟動多個執行緒，我們便可以讓他們同時執行。

在下一篇將會介紹如何啟動執行緒。


---

# 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-1.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.
