线程池使用排坑之阻塞队列选型

在使用线程池时,碰到了一个奇葩问题,我没有指定任何比较器,而控制台程序执行时报错

报错信息:java.util.concurrent.FutureTask cannot be cast to java.lang.Comparable

FutureTask无法被转换为Comparable

而Comparable是java内置比较器接口,在程序中我并没有用到

代码下:

@RestController
@RequestMapping("test")
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/tryReentrantLock")
    public List<String> tryReentrantLock(String lockName){
        RedisInstanceCount redisInstanceCount = new RedisInstanceCount();
        Thread thread = new Thread(redisInstanceCount);
        thread.setDaemon(true);
        thread.start();
        return execute(lockName);
    }

    private List<String> execute(String lockName) {
        List<String> resultList = new LinkedList<>();
        ThreadPoolExecutor threadPoolExecutor = ThreadUtils.getThreadPoolExecutor();
        for (int index = 0; index < threadPoolExecutor.getMaximumPoolSize(); index++) {
            Future<String> submit = threadPoolExecutor.submit(() -> {
                return testService.tryReentranLock(lockName);
            });
            if (submit.isDone()) {
                try {
                    String result = submit.get();
                    resultList.add(result);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        resultList.forEach(System.out::println);
        return resultList;
    }
}

断点追踪,进入submit()方法

最终执行在execute方法里,再追踪进去

在execute方法执行时,判断了当前工作线程数是否小于核心线程数,然后再判断当前线程是否运行并且阻塞队列是否可用,追踪进workQueue.offer()

关键就在这个siftUpComparable()中

优先队列在执行时会通过不断地上升和下沉(这里指二叉堆实现的优先队列)保证队头元素一定是整个队列中最大或最小的,这个过程中,实现了Comparable接口,在调用siftUpComparable方法时,直接将泛型(这个泛型就是当前执行的线程对象),而我们的线程对象没有实现Comparable,类型不匹配,转换失败

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值