文章参考《Java多线程编程核心》
概述:系统中的线程可以划分优先级,优先级越高获取cpu资源多,cpu优先执行。
Java中设置优先级使用方法 Thread 中的 setPriority()方法,设置线程优先级就是告诉线程规划器先拿哪一个线程优先执行
让我们看看setPriority方法的源码:
//Java中 Thread的 setPriority的源码
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);
}
}
优先级的常量定义:
/**
* 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;
结论: 从这里我们能看到如果线程的优先级如果大于最大线程优先级(MAX_PRIORITY =10),或小于最小优先级(MIN_PRIORITY=1)则会抛出异常IllegalArgumentException;
让我们实验一下:
创建一个 MyThread2.java,把他的优先级设置为-1
public class MyThread2 extends Thread {
@Override
public void run() {
System.out.println("MyThread2 run priority" + this.getPriority());
}
public static void main(String[] args) {
MyThread2 thread2 = new MyThread2();
thread2.setPriority(-1);
thread2.start();
}
}
结果如下: