线程的优先级
在操作系统中,线程可以划分优先级,优先级较高的线程得到的cpu资源较多,也就是cpu优先执行优先级较高的线程对象中的任务。
设置线程的优先级有助于帮“线程规划器”确定在下一次选择哪个线程来优先执行。
设置线程的优先级使用的是线程对象的setPriority()方法,查看源码如下:
/**
* Changes the priority of this thread.
* <p>
* First the <code>checkAccess</code> method of this thread is called
* with no arguments. This may result in throwing a
* <code>SecurityException</code>.
* <p>
* Otherwise, the priority of this thread is set to the smaller of
* the specified <code>newPriority</code> and the maximum permitted
* priority of the thread's thread group.
*
* @param newPriority priority to set this thread to
* @exception IllegalArgumentException If the priority is not in the
* range <code>MIN_PRIORITY</code> to
* <code>MAX_PRIORITY</code>.
* @exception SecurityException if the current thread cannot modify
* this thread.
* @see #getPriority
* @see #checkAccess()
* @see #getThreadGroup()
* @see #MAX_PRIORITY
* @see #MIN_PRIORITY
* @see ThreadGroup#getMaxPriority()
*/
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);
}
}
在java中,线程的优先级分为1~10这10个等级,如果小于1或大于10,则jdk抛出IllegalArgumentException()异常。
jdk中使用三个常量来预置定义优先级的值,代码如下:
/**
* 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;
线程优先级的继承特性
在java中,线程的优先级具有继承性,比如a线程启动b线程,则b线程的优先级与a是一样的。
// class B
public class ThreadB extends Thread {
@Override
public void run() {
System.out.println("ThreadB run priority=" + this.getPriority());
}
}
// class A
public class ThreadA extends Thread {
@Override
public void run() {
System.out.println("ThreadA run priority=" + this.getPriority());
ThreadB threadB = new ThreadB();
threadB.start();
}
}
// main
public static void main(String[] args) {
threadA();
}
private static void threadA() {
System.out.println("Main begin priority=" + Thread.currentThread().getPriority());
// Thread.currentThread().setPriority(6);
System.out.println("Main end priority=" + Thread.currentThread().getPriority());
ThreadA threadA = new ThreadA();
threadA.start();
}
输出结果:
Main begin priority=5
Main end priority=5
ThreadA run priority=5
ThreadB run priority=5
解开注释Thread.currentThread().setPriority(6);后运行结果如下:
Main begin priority=5
Main end priority=6
ThreadA run priority=6
ThreadB run priority=6
线程的优先级具有规则性,即优先级越高的线程分配的cpu执行时间越多。
线程的优先级具有随机性,即优先级差距不大的两个线程获取的cpu执行时间是随机的。
综上所述:不要把线程的优先级与运行结果的顺序作为衡量的标准,优先级较高的线程并不一定每一次都要先执行完run()方法中的任务,也就是说,线程的优先级具有随机性和不确定性。