[26]线程的优先级[浅]

优先级

Thread源代码:

    /* The minimum priority that a thread can have.*/
    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;

1,5,10,最小,默认,最大。

稍微注意的就是:可以在1-10之间取任意整数,但是不能大于10或小于1

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);
        }
    }

红字的意思就是,参数大于最大优先级或是小于最小优先级,抛出无效参数异常。

并且在线程中创建的线程,默认优先级也是当前线程的优先级。

class Demo{
    public static void main(String[] args){
        PriorityThread thread=PriorityThread();
        Thread t1=new Thread(thread);
        t1.start();
    }
}

class PriorityThread implements Runnable{
    @override
    public void run(){
        System.out.println(Thread.currentThread().toString());
    }
}

输出结果:

Thread[Thread-0,5,main]

Thread-0线程名称,5则是优先级,main是所属线程组

接下来看看main的优先级

class Demo{
    public static void main(String[] args){
        System.out.println("main : "+Thread.currentThread.getPriority());
    }
}

输出结果:

main : 5

init()也写到

//code....

Thread parent = currentThread();

this.priority = parent.getPriority();

意思就是线程的优先级就是当前线程的优先级。 

注意点:设置线程优先级用setPriority(),要在线程开启前设置。

这篇文章主要为笔记。学的比较浅。

大佬的话:不要假定MAX_PRIORITY>MIN_PRIORITY。不要有逻辑依赖于优先级,因为优先级不是绝对的,取决虚拟机的版本,或是操作系统或是CPU硬件等等。

我也试了一下,并不是永远都是MAX_PRIORITY的优先权一定要大于MIN_PRIORITY。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值