阅读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只决定了线程执行优先级的权重,权重大的有较大概率先执行,但并非必定先执行