10.线程的优先级

线程的优先级(priority)

  • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,
  • 线程调度器按照优先级决定应该调度哪个线程来执行
  • 线程的优先级用数字表示,1~10
    • Tread.MIN_PRIORITY = 1;
    • Tread.MAX_PRIORITY = 10;
    • Tread.NORM_PRIORITY = 5; 默认
  • 使用以下方法获取或改变优先级
    • getPriority()
    • setPriority(int xxx)
  • 优先级的设置建议再start()调度之前
  • 优先级低只能意味者获取调度的概率低,并不是优先级低就不会被调用了,这都是看cpu的调度
package com.state;

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

        TestPriority2 p2 = new TestPriority2();

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

        t1.start();

        t2.setPriority(Thread.MIN_PRIORITY); // 1
        t2.start();

        t3.setPriority(Thread.MAX_PRIORITY); // 10
        t3.start();

        // 小于1 大于10 会抛出异常
        // t4.setPriority(-1);
        // t4.start();

        // t5.setPriority(11);
        // t5.start();
    }
}

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

猜你喜欢

转载自blog.csdn.net/weixin_56121715/article/details/123780937
今日推荐