我有以下代码的变体:
package com.test.package;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestClass {
public static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Called");
}
}
public void method() {
PriorityBlockingQueue<MyRunnable> queue = new PriorityBlockingQueue<MyRunnable>();
method2(queue);
}
public void method2(BlockingQueue<? extends Runnable> queue) {
System.out.println(queue);
// Getting error here because BlockingQueue<? extends Runnable> is not a
// subtype of BlockingQueue<Runnable>.
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(200, 200, 0L,
TimeUnit.MILLISECONDS, queue);
}
}
如您所见,我的队列与 ThreadPoolExecutor
不兼容构造函数。有什么办法可以解决这个问题,而不是将我的队列转换为 (BlockingQueue<Runnable>)
?我显然无法修补 Java 标准库。
最佳答案
不,你不应该。
你的 BlockingQueue<MyRunnable>
当然,应该只包含 MyRunnable
秒。但是 ThreadPoolExecutor
可以提交任意Runnable
任务到你给它的队列:见 execute(Runnable command)
.
如果发生这种情况,您可能会得到一个非 MyRunnable
队列中的实例。然后您尝试从您对该队列的引用(输入为 BlockingQueue<MyRunnable>
)进行轮询,并获得 ClassCastException
.
简单的例子:
PriorityBlockingQueue<MyRunnable> queue = new PriorityBlockingQueue<>();
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(200, 200, 0L,
TimeUnit.MILLISECONDS, queue);
threadPool.execute(new WhateverRunnable());
MyRunnable myRunnable = queue.poll(); // this could throw ClassCastException
如果 queue.poll()
上面的代码将抛出异常在线程池有机会出列 WhateverRunnable
之前发生实例。
关于java - 如何使我的泛型代码与此方法签名兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24636199/