面试官:线程的优先级范围是多少?超出范围会如何?

本文探讨了Java中线程的优先级范围,指出其最小值为1,最大值为10,且默认优先级为5。虽然高优先级线程通常先执行,但实际调度仍取决于CPU。线程的优先级应在启动前设置,若设置值超出范围,将抛出IllegalArgumentException异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.1线程优先级范围

最小为1

最大为10

1.2 线程默认的优先级

默认为5

1.3 优先级高的并不一定是最先执行的,最终由cpu调用,但是大多数是优先级高的先执行

1.4 先设置优先级,再执行start启动线程

1.5 如果优先级不在范围内,则抛出异常IllegalArgumentException

定义线程优先级源码:

/**
     * 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;

优先级赋值方法:

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

优先级取值方法:

public final int getPriority() {
        return priority;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值