Java Thread setPriority() 方法



描述

Java Thread setPriority() 方法更改此執行緒的優先順序。

宣告

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

public final void setPriority(int newPriority)

引數

newPriority − 這是要設定此執行緒的優先順序。

返回值

此方法不返回任何值。

異常

  • IllegalArgumentException − 如果優先順序不在 MIN_PRIORITY 到 MAX_PRIORITY 範圍內。

  • SecurityException − 如果當前執行緒無法修改此執行緒。

示例:設定執行緒的優先順序

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

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);
   
      int count = Thread.activeCount();
      System.out.println("currently active threads = " + count);
   }
}

輸出

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

Thread = Thread[Admin Thread,1,main]
currently active threads = 1

示例:設定執行緒的最高優先順序

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

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);
   
      int count = Thread.activeCount();
      System.out.println("currently active threads = " + count);
   }
}

輸出

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

Thread = Thread[Admin Thread,1,main]
currently active threads = 1

示例:設定執行緒的最低優先順序

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

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);
   
      int count = Thread.activeCount();
      System.out.println("currently active threads = " + count);
   }
}

輸出

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

Thread = Thread[Admin Thread,1,main]
currently active threads = 1
java_lang_thread.htm
廣告