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

报错信息: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,类型不匹配,转换失败