更改Java中的线程优先级

可以通过实现Runnable接口并覆盖该run()方法来创建线程。然后可以创建一个Thread对象并start()调用该方法。

线程优先级确定何时向线程提供处理器以及其他资源。可以使用setPriority()Thread类的方法进行更改。

给出了一个演示如何使用setPriority()Java中的方法更改线程优先级的程序,如下所示:

示例

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("\nChanging 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("\nChanged 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("\n" + Thread.currentThread().getName());
      System.out.println("\nDefault 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