在 Java 中更改執行緒優先順序


可以透過實現 Runnable 介面並重寫 run() 方法來建立一個執行緒。然後可以建立一個 Thread 物件並呼叫 start() 方法。

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

以下給出了一個程式,演示如何在 Java 中使用 setPriority() 方法更改執行緒優先順序

示例

 線上演示

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();
      ThreadDemo thread3 = new ThreadDemo();
      ThreadDemo thread4 = new ThreadDemo();
      ThreadDemo thread5 = new ThreadDemo();
      System.out.println("Default thread priority of Thread 1: " + thread1.getPriority());
      System.out.println("Default thread priority of Thread 2: " + thread2.getPriority());
      System.out.println("Default thread priority of Thread 3: " + thread3.getPriority());
      System.out.println("Default thread priority of Thread 4: " + thread4.getPriority());
      System.out.println("Default thread priority of Thread 5: " + thread5.getPriority());
      System.out.println("
Changing the default thread priority using the setPriority() method");       thread1.setPriority(7);       thread2.setPriority(3);       thread3.setPriority(9);       thread4.setPriority(2);       thread5.setPriority(8);       System.out.println("
Changed thread priority of Thread 1: " + thread1.getPriority());       System.out.println("Changed thread priority of Thread 2: " + thread2.getPriority());       System.out.println("Changed thread priority of Thread 3: " + thread3.getPriority());       System.out.println("Changed thread priority of Thread 4: " + thread4.getPriority());       System.out.println("Changed thread priority of Thread 5: " + thread5.getPriority());       System.out.println("
" + Thread.currentThread().getName());       System.out.println("
Default thread priority of Main Thread: " + Thread.currentThread().getPriority());       Thread.currentThread().setPriority(10);       System.out.println("Changed thread priority of Main Thread: " + Thread.currentThread().getPriority());    } }

輸出

Default thread priority of Thread 1: 5
Default thread priority of Thread 2: 5
Default thread priority of Thread 3: 5
Default thread priority of Thread 4: 5
Default thread priority of Thread 5: 5
Changing the default thread priority using the setPriority() method
Changed thread priority of Thread 1: 7
Changed thread priority of Thread 2: 3
Changed thread priority of Thread 3: 9
Changed thread priority of Thread 4: 2
Changed thread priority of Thread 5: 8
main
Default thread priority of Main Thread: 5
Changed thread priority of Main Thread: 10

更新日期:2019 年 7 月 30 日

610 次觀看

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告