# 實作 RUNNABLE 介面

若本身類別已經繼承了其他父類別，但又想繼承 Thread 類別，這時就會遇到 Java 無法多重繼承。\
想到多重繼承就會想到 介面，在［JAVA］多重繼承中提到：透過 介面 就能達到多重繼承。

Java 提供了 Runnable 介面，有抽象函數 run() ；因此我們只需要定義 run() 即可。

改寫 [啟動執行緒](/java-15/java-15-2.md#wan-zheng-cheng-shi-ma) 中的範例：

讓我們先實作介面

```
class multi_Test implements Runnable
{
   private String name;
   public multi_Test(String str)
   {
      name=str;
   }
   public void run()
   {
   }
}
```

且詳細定義 run函數

```
public void run()
   {
      for(int i=0;i<4;i++)
      {
         for(int j=0;j<100000000;j++);
         System.out.println(id+" is running..");
      }
   }
```

而在main() 中：我們建立物件後，再分別產生 Thread 類別的物件 來呼叫 start() 啟動執行緒

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

## 完整程式碼

```
class multi_Test implements Runnable
{
   private String name;
   public multi_Test(String str)
   {
      name=str;
   }
   public void run()
   {
      for(int i=0;i<3;i++)
      {
         for(int j=0;j<100000000;j++);
         System.out.println(id+" is running..");
      }
   }
}

public class multi_thread_3
{
   public static void main(String args[])
   {
      multi_Test apple=new multi_Test("apple");
      multi_Test pen=new multi_Test("pen");
      Thread m1=new Thread(apple);
      Thread m2=new Thread(pen);
      m1.start();
      m2.start();
   }
}

```

## 整理

Ｑ：那麼該使用 Thread類別 還是 Runnable介面呢？\
Ａ：其實都可以，了解該類別是否有繼承其他類別。因為類別只能繼承一個類別。

那如果使用多執行緒的類別已經繼承其他類別，就必須實作。\
我們可以這麼寫：

```
class multi_Test extends m_test implements Runnable
{
  ...
}
```

以上意思：multi\_Test 類別繼承 m\_test 類別 並實作 Runnable 介面\
這麼一來multi\_Test 可以使用多執行緒，又能繼承 m\_test 類別。<br>


---

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