【多线程学习】线程的优先级

「这是我参与11月更文挑战的第8天,活动详情查看:2021最后一次更文挑战

JAVA提供了一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度那个线程来执行。

线程的优先级用数字表示,范围1~10

Thread.MIN_PRIORITY = 1

Thread.NORM_PRIORITY = 5

Thread.MAX_PRIORITY = 10

改变和设置线程优先级的方式

setPriority(), getPriority()

进入Thread类查看源码可以发现

最小的优先级为1,最大的优先级为10,默认的优先级为5

image.png

在查看它的setPriority(),可以看到当设置的优先级数字大于最大值或者小于最小值都会报错,如果不在设置会给一个默认值
image.png

自己写一个demo测试整个过程

public class TestPriority {

    public static void main(String[] args) {
        ThreadPriority priority = new ThreadPriority();

        Thread t1 = new Thread(priority);
        Thread t2 = new Thread(priority);
        Thread t3 = new Thread(priority);
        Thread t4 = new Thread(priority);
        Thread t5 = new Thread(priority);

        t1.start(); //默认优先级

        t2.setPriority(1);
        t2.start();

        t3.setPriority(11); //超过最大值
        t3.start();

        t4.setPriority(-1); //小于最小值
        t4.start();

        t5.setPriority(Thread.MAX_PRIORITY);
        t5.start();

    }

}

class ThreadPriority implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
    }
}

复制代码

这里设置了大于最大值,和小于最小值,正常的话输出结果会报错

查看输出结果,报错了
image.png

再次设置正常值查看运行结果

image.png

image.png

运行了两次,第二次的运行结果是按照设置的优先级由高到低依次执行,但是第一次的运行结果就不是。由此得出

优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是要看CPU的调度

优先级的设置建议在start()调度前