Java 中的最低和最高優先順序執行緒


執行緒優先順序決定了處理器如何提供給執行緒以及其他資源。它可以使用 Thread 類的 setPriority() 方法更改。

Java 中的執行緒優先順序有三個靜態變數,即 MIN_PRIORITY、MAX_PRIORITY 和 NORM_PRIORITY。這些變數的值分別為 1、10 和 5。

如下所示給出了一個展示這一點的程式

示例

 即時演示

public class ThreadDemo extends Thread {
   public void run() {
      System.out.println("Running...");
   }
   public static void main(String[] args) {
      ThreadDemo thread1 = new ThreadDemo();
      ThreadDemo thread2 = new ThreadDemo();
      System.out.println("Default thread priority of Thread 1: " + thread1.getPriority());
      System.out.println("Default thread priority of Thread 2: " + thread2.getPriority());
      thread1.setPriority(MAX_PRIORITY);
      thread2.setPriority(MIN_PRIORITY);
      System.out.println("
The maximum thread priority of Thread 1 is: " + thread1.getPriority());       System.out.println("The minimum thread priority of Thread 2 is: " + thread2.getPriority());       System.out.println("
" + Thread.currentThread().getName());       System.out.println("Default thread priority of Main Thread: " + Thread.currentThread().getPriority());       Thread.currentThread().setPriority(MAX_PRIORITY);       System.out.println("The maximum thread priority of Main Thread is: " + Thread.currentThread().getPriority());    } }

輸出

Default thread priority of Thread 1: 5
Default thread priority of Thread 2: 5
The maximum thread priority of Thread 1 is: 10
The minimum thread priority of Thread 2 is: 1
main
Default thread priority of Main Thread: 5
The maximum thread priority of Main Thread is: 10

更新於: 30-Jul-2019

3 千+ 瀏覽量

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.