现在操作系统基本采用时分的形式调度运行的线程,操作系统会分出一个个时间片,线程会分配到若干的时间片,当线程的时间片用完了,就会执行发生线程调度,并等待这下次时间片的分配。线程分配到的时间片的多少,直接决定了线程占用cpu资源的多少,而线程优先级则决定了线程需要多或者少分配cpu资源的属性。
线程通过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;
默认的优先级为5
如果setPriority(int newPriority)的参数newPriority小于1或者大于10时,那么抛出IllegalArgumentException异常。
设置线程优先级时,针对频繁阻塞的线程,需要设置较高的优先级,而偏重计算的线程,则需要设置较低的优先级。
线程的优先级具有继承性,如果线程A启动了线程B,那么线程B将具有和线程A一样的优先级。
public class MyThread2 extends Thread {
@Override
public void run() {
System.out.println("MyThread2的优先级为:"+this.getPriority());
}
}
public class MyThread1 extends Thread {
@Override
public void run() {
this.setPriority(8);
System.out.println("MyThread1的优先级:"+this.getPriority());
System.out.println("启动线程MyThread2");
MyThread2 myThread2 = new MyThread2();
myThread2.start();
}
}
public class Runner {
public static void main(String[] args) {
MyThread1 myThread1 = new MyThread1();
myThread1.start();
}
}
执行结果如下:
MyThread1的优先级:8
启动线程MyThread2
MyThread2的优先级为:8
但是,在不同的JVM和操作系统上,线程规划会有所差异,有些操作系统设置会完全忽略对线程优先级的设定。