首页 > 文章列表 > 多线程中的Java线程优先级

多线程中的Java线程优先级

java多线程 多线程编程 线程优先级
140 2023-09-16

在多线程的情况下,线程调度程序根据不同的条件将线程分配给特定的进程。 他们的优先事项。 java 线程具有预先分配的优先级。除此之外,java虚拟 机器还可以为线程分配优先级或由程序员明确指定。范围为 线程优先级的值介于 1 到 10(含)之间。三个静态变量 与优先级相关的有 -

  • MAX_PRIORITY - 线程拥有的最大优先级,默认值为 10。

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

  • MIN_PRIORITY - 线程具有的最小优先级,默认值为 1。< /p>

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

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

它们被打印在控制台上。接下来,使用以下方法为 Demo 实例分配优先级: ‘设置优先级’函数。输出显示在控制台上。打印线程的名称 借助“getName”功能在屏幕上显示。