# 執行緒的順序

在前篇使用了 join() 來控制安排執行緒。那麼執行緒一多，我們可以安排哪些執行緒優先順序是較高的。

> Java 執行緒的優先順序是使用 1\~10來表示，數字大代表優先權較高（意指先執行）。

有兩個函數與優先權相關：

* setPriority() 用來設定優先順序
* getPriority() 用來取得順序之值

而在 setPriority() 的引數可以使用以下三個常用的代碼：

* MAX\_PRIORTY       最大優先權數值
* MIN\_PRIORTY        最小優先權數值
* NORM\_PRIORTY    系統預設

透過範例來了解一下用法吧～

修改[前一篇的範例](/java-15/java-15-join.md#wan-zheng-cheng-shi-ma-zheng-que)：此次建立5個執行緒，並在執行前設定優先權。

首先建立5個執行緒

```
multi_Test apple=new multi_Test("red");
multi_Test banana=new multi_Test("yellow");
multi_Test grape=new multi_Test("purple");
multi_Test cloud =new multi_Test("white");
multi_Test grass=new multi_Test("green");
```

設定優先權（使用常見的代碼）

```
apple.setPriority(Thread.MAX_PRIORITY);
banana.setPriority(Thread.MIN_PRIORITY);
```

除了使用常見代碼之外，也可以直接設定1\~10的引數

```
cloud.setPriority(3);
grass.setPriority(6);
```

## 完整程式碼

```
class multi_Test
{
   private String name;
   public multi_Test(String str)
   {
      name=str;
   }
   public void show()
   {
      for(int i=0;i<3;i++)
      {
         try
         {
            sleep((int)(1000*Math.random()));
         }
         catch(InterruptedException e){}
         System.out.println(name+" 執行中"+this.getPriority());
      }
   }
}

public class multi_thread_3
{
public static void main(String args[])
{
   multi_Test apple=new multi_Test("red");
   multi_Test banana=new multi_Test("yellow");
   multi_Test grape=new multi_Test("purple");
   multi_Test cloud =new multi_Test("white");
   multi_Test grass=new multi_Test("green");

   apple.setPriority(Thread.MAX_PRIORITY);
   banana.setPriority(Thread.MIN_PRIORITY);
   cloud.setPriority(3);
   grass.setPriority(6);

   apple.start();
   banana.start();
   grape.start();
   cloud.start();
   grass.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-5.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.
