Java 執行緒 getPriority() 方法



描述

Java Thread getPriority() 方法返回此執行緒的優先順序。

宣告

以下是 java.lang.Thread.getPriority() 方法的宣告

public final int getPriority()

引數

返回值

此方法返回此執行緒的優先順序。

異常

示例:獲取執行緒的優先順序

以下示例演示了 Java Thread getPriority() 方法的使用。在此示例中,我們使用 main 方法中的 activeThread() 方法檢索當前活動的執行緒,並使用 setPriority() 方法將優先順序設定為 1,然後使用 getPriority() 方法列印執行緒優先順序。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      t.setName("Admin Thread");
      // set thread priority to 1
      t.setPriority(1);
     
      // prints the current thread
      System.out.println("Thread = " + t);
      System.out.println("Thread Priority = " + t.getPriority());
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Thread = Thread[#1,Admin Thread,1,main]
Thread Priority = 1

示例:獲取執行緒的優先順序

以下示例演示了 Java Thread getPriority() 方法的使用。在此示例中,我們使用 main 方法中的 activeThread() 方法檢索當前活動的執行緒,並使用 setPriority() 方法將優先順序設定為 MAX_PRIORITY,然後使用 getPriority() 方法列印執行緒優先順序。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      t.setName("Admin Thread");
      // set thread priority to MAX_PRIORITY
      t.setPriority(Thread.MAX_PRIORITY);
     
      // prints the current thread
      System.out.println("Thread = " + t);
      System.out.println("Thread Priority = " + t.getPriority());
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Thread = Thread[#1,Admin Thread,10,main]
Thread Priority = 10

示例:獲取執行緒的最低優先順序

以下示例演示了 Java Thread getPriority() 方法的使用。在此示例中,我們使用 main 方法中的 activeThread() 方法檢索當前活動的執行緒,並使用 setPriority() 方法將優先順序設定為 MIN_PRIORITY,然後使用 getPriority() 方法列印執行緒優先順序。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      t.setName("Admin Thread");
      // set thread priority to MIN_PRIORITY
      t.setPriority(Thread.MIN_PRIORITY);
     
      // prints the current thread
      System.out.println("Thread = " + t);
      System.out.println("Thread Priority = " + t.getPriority());
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Thread = Thread[#1,Admin Thread,1,main]
Thread Priority = 1
java_lang_thread.htm
廣告