线程优先级

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

线程的优先级用数字表示,范围从1~10
Thread.MIN_PRIORITY = 1;
Thread.MAX_PRIORITY=10;
Thread.NORM_PRIORITY=5;(默认的)

使用一下方法改变和获取优先级:
setPriority() 、getPriority()

/**
 * @author DB
 * @title: ThreadPriority
 * @projectName XianCheng
 * @description: 测试线程优先级
 * @date 2021/11/915:45
 */
public class ThreadPriority {
     
    public static void main(String[] args) {
     
        System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();
        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);

        t1.setPriority(1);
        t1.start();

        t2.setPriority(4);
        t2.start();

        t3.setPriority(6);
        t3.start();

        t4.setPriority(7);
        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());
    }
}

注意:
1.优先级的设定是在start()之前t1.setPriority(1);t1.start();
2.优先级的高低只是意味着获得调度概率的高低,并不意味着越高越先执行,这得看CPU的调度。如上方代码的结果
线程优先级_第1张图片

你可能感兴趣的:(操作系统,java,多线程,优先级)