Java并发编程入门 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

源码分析

我们现在来看看JDK在线程上的源代码

首先是设置优先级的方法:

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);
        }
}

这也是一个final方法,不能被覆盖,我们发现,JDK中设置优先级要有一个最大值和最小值的,我们来看看这两个值:

public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;

从这里我们可以看出来线程的优先级分为1-10,中间还有一个值为5.那么5是什么呢?就是线程优先级的默认值,在我们程序中,如果没有规定线程的优先级,那么线程优先级为5。

请读者查看JDK中源代码有关线程优先级的代码。