线程优先级

suaxi
2020-11-26 / 0 评论 / 84 阅读 / 正在检测是否收录...

线程优先级

  • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度按照优先级来调度执行线程
  • 优先级范围:1~10

    • Thread.MIN_PRIORITY = 1
    • Thread.MAX_PRIORITY = 10
  • 设置方法

注:1、线程优先级应先设置再启动

​ 2、优先级低只意味着获得调度的概率低,并不是优先级低就不会被调用,最终结果由CPU调度决定

package com.thread.state;

/**
 * @Author suaxi
 * @Date 2020/11/26 11:11
 * 测试线程优先级
 */
public class TestPriority {
    public static void main(String[] args) {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName()+"---->"+Thread.currentThread().getPriority());

        //设置优先级
        Mypeiority mypeiority = new Mypeiority();
        Thread t1 = new Thread(mypeiority);
        Thread t2 = new Thread(mypeiority);
        Thread t3 = new Thread(mypeiority);
        Thread t4 = new Thread(mypeiority);
        Thread t5 = new Thread(mypeiority);

        //先设置,再启动
        t1.start();
        t2.setPriority(3);
        t2.start();
        t3.setPriority(Thread.MAX_PRIORITY); //MAX_PRIORITY=10
        t3.start();
        t4.setPriority(Thread.MIN_PRIORITY);
        t4.start();
        t5.setPriority(7);
        t5.start();
    }
}

class Mypeiority implements Runnable{

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

评论 (0)

取消