多线程中的 Java 线程优先级

javaserver side programmingprogramming

在多线程情况下,线程调度程序根据线程的优先级将其分配给特定进程。Java 线程具有预先分配的优先级。除此之外,Java 虚拟机还可以为线程分配优先级或由程序员明确指定。线程优先级的值范围在 1 到 10(含)之间。与优先级相关的三个静态变量是 −

  • MAX_PRIORITY − 线程具有的最大优先级,其默认值为 10。

  • NORM_PRIORITY − 线程具有的默认优先级,其默认值为 5。

  • MIN_PRIORITY −线程具有的最小优先级,其默认值为 1。

Java 中的 ‘getPriority()’ 方法有助于返回绑定到它的线程优先级值。

‘setPriority()’ 方法可更改给定线程的优先级值。当线程优先级小于 1 或大于 10 时,它会抛出 IllegalArgumentException。

示例

import java.lang.*;
public class Demo extends Thread{
   public void run(){
      System.out.println("Now, inside the run method");
   }
   public static void main(String[]args){
      Demo my_thr_1 = new Demo();
      Demo my_thr_2 = new Demo();
      System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority());
      System.out.println("The thread priority of first thread is : " +       my_thr_2.getPriority());
      my_thr_1.setPriority(5);
      my_thr_2.setPriority(3);
      System.out.println("The thread priority of first thread is : " +    my_thr_1.getPriority());
      System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority());
      System.out.print(Thread.currentThread().getName());
      System.out.println("The thread priority of main thread is : " +
      Thread.currentThread().getPriority());
      Thread.currentThread().setPriority(10);
      System.out.println("The thread priority of main thread is : " +
      Thread.currentThread().getPriority());
   }
}

输出

The thread priority of first thread is : 5
The thread priority of first thread is : 5
The thread priority of first thread is : 5
The thread priority of first thread is : 3
The thread priority of main thread is : 5
The thread priority of main thread is : 10

从基类Thread继承了一个名为Demo的类。定义了函数‘run’并定义了相关消息。在主函数中,创建了Demo类的两个实例,并通过调用函数‘getPriority’找到它们的优先级。

它们被打印在控制台上。接下来,使用‘setPriority’函数为Demo实例分配优先级。输出显示在控制台上。借助‘getName’函数将线程的名称打印在屏幕上。


相关文章