线程池之提交优先级与执行优先级

本文探讨了在使用Java线程池时遇到的问题,即线程的执行顺序并非按提交顺序进行。分析了线程池的工作原理,提交优先级遵循核心线程、等待队列、非核心线程的顺序,而执行优先级则是核心线程优先,接着是非核心线程,最后是等待队列中的任务。通过分析`execute`方法和`runWorker`方法的逻辑,揭示了线程调度的内部机制。

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

问题发现

在使用newfixedThreadPool时设置核心线程10,最大线程20,采用arrayBlockingQueue10。
在for循环里打印i,以及线程id,发现线程的顺序是先打印1到10,然后打印21到30。也就是说后提交的数据中间输出。

提交优先级

提交优先级:就是先交付核心线程、等待队列、非核心线程。
在这里插入图片描述
代码如下:

public void execute(Runnable command) {
   
    if (command == null)
        throw new NullPointerException();
    /*
     * Proceed in 3 steps:
     *
     * 1. If fewer than corePoolSize threads are running, try to
     * start a new thread with the given command as its first
     * task.  The call to addWorker atomically checks runState and
     * workerCount, and so prevents false alarms that would add
     * threads when it shouldn't, by returning false.
     *
     * 2. If a task can be successfully queued, then we still need
     * to double-check whether we should have added a thread
     * (because existing ones died since last checking) or that
     * the pool shut down since entry into this method. So we
     * recheck state and if necessary roll back the enqueuing if
     * stopped, or start a new thread if there are none.
     *
     * 3. If we cannot queue task, then we try to add a new
     * thread.  If it fails, we know we are shut down or saturated
     * and so reject the task.
     */
    int c = ctl.get();
    // worker数量比核心线程数小,直接创建worker执行任务
    if (workerCountOf(c) < corePoolSize) {
   
        if (addWorker(command, true))
            return;
        c = ctl.get<
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值