上源码:
public static final int MIN_PRIORITY = 1;
public static final int NORM_PRIORITY = 5;
public static final int MAX_PRIORITY = 10;
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals){
...
this.priority = parent.getPriority();
...
setPriority(priority);
...
}
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);
}
}
子线程继承父线程的优先级,如果子线程在线程组中,而且父线程的优先级大于线程组的最大优先级,则子线程优先级为线程组的最大优先级。
main线程优先级默认5,低优先级为1至4,高优先级为6-10,Thread.MIN_PRIORITY为1,Thread.NORM_PRIORITY为5,Thread.MAX_PRIORITY为10。
高优先级线程不一定比低优先级线程优先执行。受CPU多核和操作系统调度策略影响。
操作系统中,进程是资源分配的最小单位,线程是最小调度单位。在windows中进程是不活动的,只是作为线程的容器。一个CPU核中低优先级线程可能比另一个CPU核中的高优先级线程执行快。
Windows优先级推进器中,低优先级线程已经频繁执行,来了高优先级线程,低优先级线程可以越级优先执行。
看实例:
/**
* @Author: ZhangHao
* @Description: 线程优先级测试
* @Date: 2020/7/23 10:56
* @Version: 1.0
*/
public class ThreadPriorityTest {
public static void main(String[] args) {
System.out.println("mian线程优先级:" + Thread.currentThread().getPriority());
Thread thread = new Thread();
System.out.println("子线程默认优先级:" + thread.getPriority());
Thread.currentThread().setPriority(7);
Thread thread111 = new Thread();
System.out.println("子线程默认优先级:" + thread111.getPriority());
ThreadGroup threadGroup1 = new ThreadGroup("threadGroup1");
System.out.println("线程组最大优先级:" + threadGroup1.getMaxPriority());
threadGroup1.setMaxPriority(6);
Thread thread1 = new Thread(threadGroup1, "thread1");
System.out.println("子线程默认优先级:" + thread1.getPriority());
thread1.setPriority(10);
System.out.println("子线程优先级:" + thread1.getPriority());
Thread thread11 = new Thread(() -> {
for(int i =0 ;i < 100;i++){
System.out.println(Thread.currentThread().getName() + " " + i);
}
});
thread11.setPriority(Thread.MAX_PRIORITY);
Thread thread22 = new Thread(() -> {
for(int i =0 ;i < 10;i++){
System.out.println(Thread.currentThread().getName() + " "+ i);
}
});
thread22.setPriority(Thread.MAX_PRIORITY);
Thread thread33 = new Thread(() -> {
for(int i =0 ;i < 10;i++){
System.out.println(Thread.currentThread().getName() + " "+ i);
}
});
thread33.setPriority(Thread.MAX_PRIORITY);
thread11.start();
thread22.start();
thread33.start();
}
}
结果:
mian线程优先级:5
子线程默认优先级:5
子线程默认优先级:7
线程组最大优先级:10
子线程默认优先级:6
子线程优先级:6
Thread-2 0
Thread-3 0
Thread-3 1
Thread-2 1
Thread-3 2
Thread-4 0
Thread-2 2
Thread-4 1
Thread-4 2
Thread-3 3
Thread-4 3
Thread-2 3
Thread-4 4
Thread-3 4
Thread-4 5
Thread-2 4
Thread-4 6
Thread-3 5
Thread-4 7
Thread-2 5
Thread-4 8
Thread-3 6
Thread-4 9
Thread-2 6
Thread-2 7
Thread-2 8
Thread-2 9
Thread-3 7
Thread-3 8
Thread-3 9