我从服务器上获取了大量图片,我想要获取一些优先级高于其他图片的图片,所以我实现了自己的ThreadPoolExecutor
,它返回了一个实现的FutureTask
Comparable
但它似乎不起作用。这些任务或多或少按照我将它们添加到队列的顺序进行处理。我调试了BlockingQueue
的{{1}},发现当我添加ThreadPoolExecutor
优先级更高时,它不会在队列顶部一直向上移动。这是代码
Runnable
我以这种方式将任务添加到池中:
public class PriorityThreadPoolExecutor extends ThreadPoolExecutor {
public PriorityThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
protected <T> RunnableFuture<T> newTaskForValue(Runnable runnable, T value) {
return new ComparableFutureTask<T>(runnable, value);
}
protected class ComparableFutureTask<T>
extends FutureTask<T> implements Comparable<ComparableFutureTask<T>> {
private Object object;
public ComparableFutureTask(Runnable runnable, T result) {
super(runnable, result);
object = runnable;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public int compareTo(ComparableFutureTask<T> o) {
if (this == o) {
return 0;
}
if (o == null) {
return -1; // this has higher priority than null
}
if (object != null && o.object != null) {
if (object.getClass().equals(o.object.getClass())) {
if (object instanceof Comparable) {
return ((Comparable) object).compareTo(o.object);
}
}
}
return 0;
}
}
}
我的public BitmapLoader(Context context){
mThreadPoolExecutor = new PriorityThreadPoolExecutor(10, Integer.MAX_VALUE,//corepool and maxpool
1L, TimeUnit.SECONDS,//keep alive idle threads
new PriorityBlockingQueue<Runnable>());//priority queue for jobs
}
public void queuePhoto(String url, ImageView imageView, int priority) {
BitmapToLoad p = new BitmapToLoad(url, imageView, priority);
final RunnableFuture<Object> futureTask =
mThreadPoolExecutor.newTaskForValue(new BitmapLoaderRunnable(p), null);
Log.d("BitmapLoader", "Scheduling job with priority " + priority);
mThreadPoolExecutor.execute(futureTask);
}
实现了BitmapLoaderRunnable
,当我调试正在调用Comparable
方法时。我究竟做错了什么?感谢
编辑:下面是我的runnables的代码
compareTo
答案 0 :(得分:8)
PriorityQueue
的头部是最少元素。因此,如果您首先需要最高优先级,则需要撤消比较。
@Override
public int compareTo(BitmapLoaderRunnable other) {
return other.bitmapToLoad.priority - this.bitmapToLoad.priority;
}