04_线程优先级

线程优先级

  • 线程调度器按照线程优先级来决定应调度那个线程来执行
  • 优先级的设定建议在start()调用前
  • 优先级低只是表示获得调度的概率低,并不是绝对先调用优先级高的线程后调用优先级低的
  • 优先级不代表绝对的调度先后顺序
  • 优先级用数值 1 - 10 来表示
  • Thread类提供了三个常量
    1. NORM_PRIORITY —— 5 默认
    2. MIN_PRIORITY —— 1
    3. MAX_PRIORITY —— 10
// 设置线程对象的优先级
Thread t1 = new Thread(线程对象);
t1.setPriority(Thread.MAX_PRIORITY);

// 获取线程对象的优先级
Thread.currentThread().getPriority()
示例:
package com.tsymq.thread.threadmore;

public class ThreadPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "优先级: " + Thread.currentThread().getPriority());
    }

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

        Thread t1 = new Thread(tp, "a");
        Thread t2 = new Thread(tp, "b");
        Thread t3 = new Thread(tp, "c");
        Thread t4 = new Thread(tp, "d");
        Thread t5 = new Thread(tp, "e");
        Thread t6 = new Thread(tp, "f");

        // 在调用start()之前设置优先级
        t1.setPriority(10);
        t2.setPriority(10);
        t3.setPriority(10);
        t4.setPriority(1);
        t5.setPriority(1);
        t6.setPriority(1);

        // 开启线程
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
    }
}
结果:
c优先级: 10
d优先级: 1
a优先级: 10
b优先级: 10
e优先级: 1
f优先级: 1

其中a、b、c线程的优先级为10,d、e、f的为1,结果d还是在a、b之前获得了调度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值