首页 > 爪哇 > java教程 > 正文

多线程中的Java线程优先级

王林
发布: 2023-09-06 14:21:06
转载
690 人浏览过

多线程中的Java线程优先级

在多线程的情况下,线程调度程序根据不同的条件将线程分配给特定的进程。 他们的优先事项。 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
登录后复制

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

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

以上是多线程中的Java线程优先级的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!