您的位置 首页 java

Java 17 多线程 Thread 的优先级

Java 17 多线程 Thread 的优先级

默认优先级

Thread 中默认定义了三种优先级别,分别是: MIN_PRIORITY, NORM_PRIORITY,MAX_PRIORITY。

定义如下:

 /**
 * The minimum priority that a thread can have.
 */
public  static  final int MIN_PRIORITY = 1;

/**
  * The default priority that is assigned to a thread.
  */
public static final int NORM_PRIORITY = 5;

/**
  * The maximum priority that a thread can have.
  */
public static final int MAX_PRIORITY = 10;  

Java 线程 的优先级分为 10 个等级,即 1~10,通过源码可以看到,如果小于 1 或大于 10,该方法将抛出异常 throw new IllegalArgument Exception ()。

 if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
    throw new IllegalArgumentException();
}  

可以通过以下的方法设置。

 public final  void  setPriority(int newPriority)   

演示代码如下:

 System.out.println("main 线程的优先级: " + Thread.currentThread().getPriority());
System.out.println("设置 main 线程的优先级设置为 7");
Thread.currentThread().setPriority(7);
System.out.println("main 线程的优先级: " + Thread.currentThread().getPriority());  

其中 Thread.currentThread() 代表着当前线程。

线程优先级具有继承特性

在 Java 中, 优先级在线程的启动运行中将被继承,比如 Thread A 线程启动 Thread B 线程,则 Thread B 线程的优先级与 Thread A 是一样的。

根据个人的使用和测试,想要继承线程的优先级,必须在创建阶段(New)前就设置优先级,否则就无法继承优先级了。

代码演示效果如下:

优先级并不绝对

虽然线程可以设置优先级,但是这个优先级并不是绝对的优先。在运行中只是 CPU 会尽量记住是尽量将执行的资源优先给优先级别比较高的线程。

用个案例演示一下:

首先定义两个线程

 class CustomThread  extends  Thread {
    @Override
    public void run() {
        String msg = this.getName() + "-CustomThread -优先级别 " + this.getPriority();
        long startTime = System.currentTimeMillis();
        long count = 0;
        for (int i = 0; i < 500000000; i++) {
           count =  count + i;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("t" + msg + "总用时: " + (endTime - startTime) + " 毫秒");
    }
}  

里面的代码几乎一致,只有描述信息做了些调整,为了更方便的查看执行效果。

main 方法代码如下:

 for (int i = 0; i < 5; i++) {
    CustomThread customThread = new CustomThread();
    customThread.setPriority(1);
    CustomThread2 customThread2 = new CustomThread2();
    customThread2.setPriority(10);
    customThread.start();
    customThread2.start();
}  

完整代码如下:

查看运行效果:

可以看到优先级别比较高的可能会优先执行,或者大部分能先执行。多执行几遍,看到的效果是不一样的。本次运行的都是优先级别高的先执行了。再执行一下, 看看效果,如下图:

这里不能把运行结果的顺序和线程的优先级作为比较, 优先级别比较高,但是不代表都最先执行完,这些都是不确定以及随机性的。看 CPU 怎么分配了。

写个小例子来演示一些优先级别对结果的影响。

定义一个线程类

 class CustomThread extends Thread {
     private  long index = 0;

    public long getIndex() {
        return index;
    }

    @Override
    public void run() {
         boolean  runFlag = true;
        while (runFlag) {
            try {
                if(this.isInterrupted()){
                    runFlag = false;
                }
                index += 1;
            } catch (Exception e) {
                runFlag = false;
            }
        }
    }
}  

复制上面的代码,定义 CustomThread2 的类。

并编写 main 方法。执行 5 次,并每次等待 5 秒钟,查看执行的数据。这里只是生成了一个索引值,一直累加 索引 值,一直到程序发起了中断。

 for (int i = 0; i < 5; i++) {
    CustomThread customThread = new CustomThread();
    customThread.setPriority(2);
    CustomThread2 customThread2 = new CustomThread2();
    customThread2.setPriority(8);
    customThread.start();
    customThread2.start();
    TimeUnit.SECONDS.sleep(10);
    customThread.interrupt();
    customThread2.interrupt();
    System.out.println("customThread : " + customThread.getIndex());
    System.out.println("customThread2: " + customThread2.getIndex());
}  

完整代码如下:

代码里演示的是5秒, 这里时间越长,影响的效果越明显。

优先级的知识点, 大概就这些了。 感谢您的阅读。

每天一个新知识点。过了半个月,一个月,就是 N 个知识点了。 希望今天的你,比昨天的你更上一层楼。今天你掌握新的知识点了吗?

文章来源:智云一二三科技

文章标题:Java 17 多线程 Thread 的优先级

文章地址:https://www.zhihuclub.com/181607.shtml

关于作者: 智云科技

热门文章

网站地图