Java 线程优先级2025 年 3 月 28 日 | 阅读 4 分钟 每个线程都有一个优先级。优先级由1到10之间的数字表示。在大多数情况下,线程调度程序根据线程的优先级调度线程(称为抢占式调度)。但这并不能保证,因为它取决于JVM规范选择哪种调度方式。请注意,Java程序员不仅可以通过JVM在Java程序中显式地为线程分配优先级。 线程优先级的 Setter 和 Getter 方法让我们讨论线程优先级的 setter 和 getter 方法。 public final int getPriority(): java.lang.Thread.getPriority() 方法返回给定线程的优先级。 public final void setPriority(int newPriority): java.lang.Thread.setPriority() 方法更新或将线程的优先级分配给 newPriority。如果 newPriority 的值超出范围(最小1,最大10),该方法将抛出 IllegalArgumentException。 Thread 类中定义的 3 个常量
线程的默认优先级是 5 (NORM_PRIORITY)。MIN_PRIORITY 的值为 1,MAX_PRIORITY 的值为 10。 线程优先级示例文件名: ThreadPriorityExample.java 输出 Priority of the thread th1 is : 5 Priority of the thread th2 is : 5 Priority of the thread th2 is : 5 Priority of the thread th1 is : 6 Priority of the thread th2 is : 3 Priority of the thread th3 is : 9 Currently Executing The Thread : main Priority of the main thread is : 5 Priority of the main thread is : 10 我们知道,在线程执行时,高优先级线程将优先于低优先级线程。但是,也存在两个线程具有相同优先级的情况。所有对线程进行管理的处理都由Java线程调度程序完成。请参考以下示例,以了解如果两个线程具有相同的优先级会发生什么。 文件名: ThreadPriorityExample1.java 输出 Priority of the main thread is : 7 Priority of the thread th1 is : 7 解释: 如果有两个优先级相同的线程,则无法预测哪个线程将首先获得执行机会。执行顺序取决于线程调度程序的算法(先来先服务、轮询等)。 IllegalArgumentException 示例我们知道,如果 getPriority() 方法的参数 newPriority 的值超出范围(1到10),我们将得到 IllegalArgumentException。让我们通过一个例子来观察。 文件名: IllegalArgumentException.java 当我们执行上述程序时,会得到以下异常 Exception in thread "main" java.lang.IllegalArgumentException at java.base/java.lang.Thread.setPriority(Thread.java:1141) at IllegalArgumentException.main(IllegalArgumentException.java:12) 下一个主题Java中的守护线程 |
我们请求您订阅我们的新闻通讯以获取最新更新。