# 啟動執行緒

在上篇 [認識多執行緒](/java-15/java-15-1.md) 當中，提了一個不好的範例做示範。\
那我們該如何啟動多個執行緒？

* 建立延伸自 Thread 類別的子類別
* 執行緒必須寫在 run() 函數中

滿足以上兩點便可啟動執行緒。那麼一定會有疑惑：\
建立子類別？ run() 函數？

Thread 就是執行緒的意思，他存放在 java.lang 類別庫當中，平時會自動載入。\
而 run() 是Thread類別當中的一個函數。

那麼瞭解了這些，我們該怎麼啟動執行緒呢？

```
class 類別名稱 extends Thread
{
   資料成員;
   函數;
   run()
   {
     //執行緒
   }
}
```

會建立子類別的目的，是我們可以進行 override 改寫的動作，改寫來自Thread類別當中的 run() 函數。

讓我們修改在［Java］多執行緒（基本觀念）當中不好的範例做示範：

首先建立子類別：

```
class multi_Test extends Thread
{
   private String name;
   public CTest(String str)
   {
      name=str;
   }
   public void run()
   {
      //執行緒
   }
}
```

並將執行緒寫在run()函數中：

```
public void run()
   {
      for(int i=0;i<3;i++)
      {
         for(int j=0;j<100000000;j++);
         System.out.println(name);
      }
   }
```

在main() 中：使用 start來呼叫。

```
multi_Test apple=new multi_Test("apple");
multi_Test pen=new multi_Test("pen");
apple.start();
pen.start();
```

這時疑問來了，為什麼要使用 start() ？\
如果直接呼叫 run() ，這樣並無法啟動執行緒，只是再將執行緒執行一遍而已；\
因此結果只是會與在［Java］多執行緒（基本觀念）當中，不好的範例相同。

因為我們繼承了來自 Thread 類別，也會繼承當中的 start() 。\
而這個 start() 會在 scheduler 排程器中登入執行緒，當執行緒開始執行 run() 才被呼叫。

## 完整程式碼

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

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


---

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