线程的优先级

阅读Thread源码

阅读Thread的源码我们可以发现

    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

Thread类有三个整形常量,分别赋予了最小优先级,最大优先级,默认优先级

 public final void setPriority(int newPriority) {
        ThreadGroup g;
        checkAccess();
        if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
            throw new IllegalArgumentException();
        }
        if((g = getThreadGroup()) != null) {
            if (newPriority > g.getMaxPriority()) {
                newPriority = g.getMaxPriority();
            }
            setPriority0(priority = newPriority);
        }
    }

在setPriority也就是设置优先级方法中的第四行,我们得知,如果传入的优先级参数大于1或小于10便会抛出异常

实现优先级的展示案例

java
package com.design;

public class ShowPriority extends Thread {

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

    public static void main(String[] args) {
        Thread thread1 = new Thread(new ShowPriority(),"线程一");
        Thread thread2 = new Thread(new ShowPriority(),"线程二");
        Thread thread3 = new Thread(new ShowPriority(),"线程三");
        Thread thread4 = new Thread(new ShowPriority(),"线程四");
        thread1.setPriority(9);
        thread2.setPriority(7);
        thread3.setPriority(4);
        thread4.setPriority(1);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        System.out.println("主线程"+Thread.currentThread().getPriority());




    }


}

以上demo便实现了 不同优先级的线程执行顺序的展示。有的小伙伴执行了这部分代码后发现,执行结果与预料不符。这是很正常的!因为Priority只决定了线程执行优先级的权重,权重大的有较大概率先执行,但并非必定先执行

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值