从头认识多线程-1.14 优先级

这一章节我们来讨论一下优先级的使用。

1.源码

主要就是set和get方法,get比较简单,不列举,下面是set的方法

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

从上面的代码我们可以看见,其实系统默认为线程分配了优先级,当我们认为的分配优先级的时候,它将跟系统的做比对,如果比原来的高的,才设置进去,如果比原来低,则不用设置


2.代码清单

package com.ray.deepintothread.ch01.topic_14;

public class PrioritySample {
	public static void main(String[] args) throws InterruptedException {
		ThreadOne threadOne = new ThreadOne();
		Thread thread = new Thread(threadOne);
		thread.setPriority(5);
		Thread thread1 = new Thread(threadOne);
		thread1.setPriority(4);
		
		thread1.start();
		thread.start();
	}
}

class ThreadOne implements Runnable {

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getPriority());
	}
}

输出:

4

5


或者是

5

4

有上面的输出可以看见,虽然我们设置了优先级,但是系统的cup会根据当前的情况自己分配时间片段。


但是,当我们把两个start的位置互换,结果基本上都是先5后4,不过由于执行的次数较少,不能下定论。


我们将在后面的章节介绍优先级的两个特性。


总结:这一章节我们主要演示多线程优先级的使用。


我的github:https://github.com/raylee2015/DeepIntoThread

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值