现代操作系统基本采用分时的形式调度运行的线程,操作系统会分出一个个的时间片,线程会分配到若干的时间片,当线程的时间片用完就会发生线程,并等待下次分配。线程分配到的时间片多少也就决定了线程使用处理器的资源多少,而线程的优先级就是决定线程需要多或者少分配一些处理器资源的线程属性
-
线程的优先级用数字表示,范围从1-10
-
Thread.MIN_PRIORITY = 1;
-
Thread.MAX_PRIORITY = 10;
-
Thread.NORM_PRIORITY = 5;
-
使用 线程.setPriority(int xxx -- 优先级范围) 设置优先级
使用 线程.getPriority() 查看线程优先级
点进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);
}
}
设置线程优先级时,针对频繁阻塞(休眠或者I/O操作)的线程需要设置较高优先级,而偏重计算(需要较多CPU升级或者偏运算)的线程则设置较低的优先级,确保处理器不会被独占
优先级只是意味着调度概率低,并不是优先级低就不会被调度。
从下面的代码示例中可以看出,优先级高的线程先被调度,线程优先级超出范围时,系统抛出IllegalArgumentException异常
public class TestPriority {
public static void main(String[] args) {
//主线程优先级
System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
//先设置优先级,在开启线程
t1.setPriority(Thread.MIN_PRIORITY);//最小优先级
t1.start();
t2.setPriority(3);
t2.start();
t3.setPriority(Thread.NORM_PRIORITY);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);//最大优先级
t4.start();
t5.setPriority(11);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
//打印线程优先级
System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
}
}