这一章节我们来讨论一下优先级的使用。
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,不过由于执行的次数较少,不能下定论。
我们将在后面的章节介绍优先级的两个特性。
总结:这一章节我们主要演示多线程优先级的使用。