gpt4 book ai didi

java - 在 ThreadPoolExecutor 中实现优先级队列

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:09:43 25 4
gpt4 key购买 nike

现在已经为此苦苦挣扎了 2 天多。

实现了我在这里看到的答案 Specify task order execution in Java

public class PriorityExecutor extends ThreadPoolExecutor {

public PriorityExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
//Utitlity method to create thread pool easily
public static ExecutorService newFixedThreadPool(int nThreads) {
return new PriorityExecutor(nThreads, nThreads, 0L,
TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>());
}
//Submit with New comparable task
public Future<?> submit(Runnable task, int priority) {
return super.submit(new ComparableFutureTask(task, null, priority));
}
//execute with New comparable task
public void execute(Runnable command, int priority) {
super.execute(new ComparableFutureTask(command, null, priority));
}
}

public class ComparableFutureTask<T> extends FutureTask<T>
implements
Comparable<ComparableFutureTask<T>> {

volatile int priority = 0;

public ComparableFutureTask(Runnable runnable, T result, int priority) {
super(runnable, result);
this.priority = priority;
}
public ComparableFutureTask(Callable<T> callable, int priority) {
super(callable);
this.priority = priority;
}

@Override
public int compareTo(ComparableFutureTask<T> o) {
return Integer.valueOf(priority).compareTo(o.priority);
}
}

我使用的Runnable:MyTask

public class MyTask implements Runnable{

public MyTask(File file, Context context, int requestId) {
this._file = file;
this.context = context;
this.requestId = requestId;
}

@Override
public void run() {
// some work
} catch (IOException e) {
Log.e("Callable try", post.toString());

}
}

我的服务:MediaDownloadService

public class MediaDownloadService extends Service {

private DBHelper helper;
Notification notification;
HashMap<Integer,Future> futureTasks = new HashMap<Integer, Future>();
final int _notificationId=1;
File file;

@Override
public IBinder onBind(Intent intent) {
return sharonsBinder;
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
helper = new DBHelper(getApplicationContext());
PriorityExecutor executor = (PriorityExecutor) PriorityExecutor.newFixedThreadPool(3);
Log.e("requestsExists", helper.requestsExists() + "");
if(helper.requestsExists()){
// map of the index of the request and the string of the absolute path of the request
Map<Integer,String> requestMap = helper.getRequestsToExcute(0);
Set<Integer> keySet = requestMap.keySet();
Iterator<Integer> iterator = keySet.iterator();
Log.e("MAP",requestMap.toString());
//checks if the DB requests exists
if(!requestMap.isEmpty()){
//execute them and delete the DB entry
while(iterator.hasNext()){
int iteratorNext = iterator.next();
Log.e("ITREATOR", iteratorNext + "");
file = new File(requestMap.get(iteratorNext));
Log.e("file", file.toString());
Log.e("thread Opened", "Thread" + iteratorNext);
Future future = executor.submit(new MyTask(file, this, iteratorNext),10);
futureTasks.put(iteratorNext, future);
helper.requestTaken(iteratorNext);
}
Log.e("The priority queue",executor.getQueue().toString());
}else{

Log.e("stopself", "stop self after this");
this.stopSelf();
}
}
return START_STICKY;
}

一直在这一行出错: future future = executor.submit(new MyTask(file, this, iteratorNext),10);

即使是 executor.submit();假设返回一个我不断得到的 future 对象

Caused by: java.lang.ClassCastException: java.util.concurrent.FutureTask cannot be cast to java.lang.Comparable
at java.util.concurrent.PriorityBlockingQueue.siftUpComparable(PriorityBlockingQueue.java:318)
at java.util.concurrent.PriorityBlockingQueue.offer(PriorityBlockingQueue.java:450)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1331)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:81)
at com.vit.infibond.test.PriorityExecutor.submit(PriorityExecutor.java:26)
at com.vit.infibond.test.MediaDownloadService.onStartCommand(MediaDownloadService.java:65)

谁能把我从这场噩梦中拯救出来?

我也尝试按照这个答案的建议去做 Testing PriorityBlockingQueue in ThreadPoolExecutor

通过添加 forNewTask 重写只是为了再次获得转换执行,但这次是为了 RunnableFuture。

我明白我的理解缺少一些基本的东西,希望得到深入的解释......

最佳答案

通过查看 java.util.concurrent.ThreadPoolExecutor 的源代码,提交 futures 时似乎很难让它正常工作。您必须覆盖感觉内部的 protected 方法并进行一些讨厌的转换。

我建议您改用 execute 方法。 Runnable 没有包装,所以它应该可以工作。

如果您需要等待作业的结果,我建议您自己实现它,以避免必须弄乱 ThreadPoolExecutor 内部结构。

关于java - 在 ThreadPoolExecutor 中实现优先级队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30574777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com