Java 中线程优先级的重要性?

javaobject oriented programmingprogramming更新于 2025/6/30 8:12:17

在多线程应用程序中,每个线程都分配有一个优先级。线程调度程序根据线程的优先级为其分配处理器,即优先级最高的线程首先分配处理器,依此类推。线程的默认优先级值为"5"。我们可以使用 Thread 类的 getPriority()  方法获取线程的优先级。

Thread 类中为线程优先级定义的三个 静态值

MAX_PRIORITY

这是最大线程优先级,值为 10。

NORM_PRIORITY

这是默认线程优先级,值为 5。

MIN_PRIORITY

这是最小线程优先级,值为 1。

语法

public final int getPriority()

示例

public class ThreadPriorityTest extends Thread {
   public static void main(String[]args) {
      ThreadPriorityTest thread1 = new ThreadPriorityTest();
      ThreadPriorityTest thread2 = new ThreadPriorityTest();
      ThreadPriorityTest thread3 = new ThreadPriorityTest();
      System.out.println("Default thread priority of thread1: " + thread1.getPriority());
      System.out.println("Default thread priority of thread2: " + thread2.getPriority());
      System.out.println("Default thread priority of thread3: " + thread3.getPriority());
      thread1.setPriority(8);
      thread2.setPriority(3);
      thread3.setPriority(6);
      System.out.println("New thread priority of thread1: " + thread1.getPriority());
      System.out.println("New thread priority of thread2: " + thread2.getPriority());
      System.out.println("New thread priority of thread3: " + thread3.getPriority());
   }
}

输出

Default thread priority of thread1: 5
Default thread priority of thread2: 5
Default thread priority of thread3: 5
New thread priority of thread1: 8
New thread priority of thread2: 3
New thread priority of thread3: 6

相关文章


有用资源