首頁  >  文章  >  Java  >  在Java中,執行緒優先權的重要性是什麼?

在Java中,執行緒優先權的重要性是什麼?

王林
王林轉載
2023-08-27 08:25:06852瀏覽

在Java中,執行緒優先權的重要性是什麼?

在多執行緒應用程式中,每個執行緒都被指派一個優先權。處理器根據執行緒的優先權(即最高優先權的執行緒先分配處理器,依此類推)由執行緒調度器分配給執行緒。執行緒的預設優先權5。我們可以使用Thread類別的getPriority()方法來取得執行緒的優先權。

在Thread類別中,定義了三個靜態值來表示執行緒的優先權:

MAX_PRIORITY

這是最高的執行緒優先權,值為 10

NORM_PRIORITY

這是預設的執行緒優先權,值為5

MIN_PRIORITY

這是最低的執行緒優先權,值為1

語法

public final int getPriority()

Example

public class ThreadPriorityTest extends Thread {
   public static void main(String[]args) {
      ThreadPriorityTest thread1 = new ThreadPriorityTest();
      ThreadPriorityTest thread2 = new ThreadPriorityTest();
      ThreadPriorityTest thread3 = new ThreadPriorityTest();
      System.out.println("Default thread priority of thread1: " + thread1.<strong>getPriority</strong>());
      System.out.println("Default thread priority of thread2: " + thread2.<strong>getPriority</strong>());
      System.out.println("Default thread priority of thread3: " + thread3.<strong>getPriority</strong>());
      thread1.setPriority(8);
      thread2.setPriority(3);
      thread3.setPriority(6);
      System.out.println("New thread priority of thread1: " + thread1.<strong>getPriority()</strong>);
      System.out.println("New thread priority of thread2: " + thread2.<strong>getPriority()</strong>);
      System.out.println("New thread priority of thread3: " + thread3.<strong>getPriority()</strong>);
   }
}

輸出

Default thread priority of thread1: 5
Default thread priority of thread2: 5
Default thread priority of thread3: 5
New thread priority of thread1: 8
New thread priority of thread2: 3
New thread priority of thread3: 6

以上是在Java中,執行緒優先權的重要性是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除