Java:线程优先级Priority

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

  • 线程的优先级用数字表示,范围从1~10(数字越大优先级越高,小于1或者大于10都会报错)

    Thread.MIN_PRIORITY = 1

    Thread.NORM_PRIORITY = 5(默认的优先级)

    Thread.MAX_PRIORITY = 10


  • getPriority() 获取优先级

  • setPriority() 改变优先级

  • 优先级低只是意味着获得调度的概率低,优先级低也可能先被调用了,这都是看CPU的调度

package com.jiemyx.thread.demo02;

public class ThreadPriority {
    public static void main(String[] args) {
        //打印出主线程的优先级
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());

        //创建线程
        MyPriority mp = new MyPriority();
        Thread t1 = new Thread(mp);
        Thread t2 = new Thread(mp);
        Thread t3 = new Thread(mp);
        Thread t4 = new Thread(mp);
        Thread t5 = new Thread(mp);
        Thread t6 = new Thread(mp);

        t1.start();

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

        t3.setPriority(4);
        t3.start();

        t4.setPriority(5);
        t4.start();

        t5.setPriority(8);
        t5.start();

        t6.setPriority(Thread.MAX_PRIORITY);    //MAX_PRIORITY=10
        t6.start();

    }
}

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

运行结果(这里结果的优先级高的也可能在后面):

main-->5
Thread-5-->10
Thread-4-->8
Thread-3-->5
Thread-0-->5
Thread-2-->4
Thread-1-->1

上一篇:鸿蒙轻内核M核源码分析:数据结构之任务就绪队列


下一篇:css学习笔记选择器、字体和文本、边框、背景