简单的线程管理 - Java - Android [英] Simple Thread Management - Java - Android
问题描述
我有一个应用程序,当用户要求过滤图像时会产生一个新线程。
I have an application which spawns a new thread when a user asks for an image to be filtered.
这是我拥有的唯一任务类型同样重要。
This is the only type of task that I have and all are of equal importance.
如果我要求太多并发线程(我想要的最大值是9),线程管理器会抛出 RejectedExecutionException 。
If I ask for too many concurrent threads (Max I ever want is 9) the thread manager throws a RejectedExecutionException.
我做的那一刻是;
// Manage Concurrent Tasks
private Queue<AsyncTask<Bitmap,Integer,Integer>> tasks = new LinkedList<AsyncTask<Bitmap,Integer,Integer>>();
@Override
public int remainingSize() {
return tasks.size();
}
@Override
public void addTask(AsyncTask<Bitmap, Integer, Integer> task) {
try{
task.execute(currentThumbnail);
while(!tasks.isEmpty()){
task = tasks.remove();
task.execute(currentThumbnail);
}
} catch (RejectedExecutionException r){
Log.i(TAG,"Caught RejectedExecutionException Exception - Adding task to Queue");
tasks.add(task);
}
}
只需将被拒绝的任务添加到队列中即可一个线程启动的时间,检查队列是否有积压。
Simply add the rejected task to a queue and the next time a thread is started the queue is checked to see if there's a backlog.
这个问题的一个明显问题是,如果最终任务在第一次尝试时被拒绝,它将会永远不会重新启动(直到它不再需要)。
The obvious issue with this is that if the final task gets rejected on its first attempt it will never be restarted (Until after it's no longer needed).
只是想知道我是否应该使用一个简单的模型来管理这类事情。我需要任务在完成后通知队列所以我知道有空间但是我不确定如何。
Just wondering if there's a simple model I should use for managing this sort of thing. I need tasks to notify the queue when they're done so I know there's space but I'm not sure how.
亲切的问候,
Gavin
推荐答案
RejectedExecutionException的原因
是因为 AsyncTask
实现了一个自己的线程池(根据Martelli先生的回答),但最多可以同时执行10个任务。为什么他们有这个限制,我不知道。
The reason for the RejectedExecutionException
is because AsyncTask
implements a thread pool of its own (per Mr. Martelli's answer), but one that is capped at a maximum of 10 simultaneous tasks. Why they have that limit, I have no idea.
因此,有一种可能性是克隆 AsyncTask
,提高限制(或无限制,这也可以通过 LinkedBlockingQueue
),并使用你的克隆。然后,也许,将更改作为补丁提交给 AsyncTask
以用于将来的Android版本。
Hence, one possibility is for you to clone AsyncTask
, raise the limit (or go unbounded, which is also possible with LinkedBlockingQueue
), and use your clone. Then, perhaps, submit the change as a patch to AsyncTask
for future Android releases.
点击此处运行Google代码搜索 AsyncTask
- 第一次点击应该是实现。
Click here to run a Google Code Search for AsyncTask
-- the first hit should be the implementation.
如果你只是想提高限额,请调整 MAXIMUM_POOL_SIZE
要像你可能需要的一样大。如果您想要无限制,请使用零参数 LinkedBlockingQueue
构造函数,而不是当前使用的构造函数。 AFAICT,其余代码可能保持不变。
If you just want to raise the limit, adjust MAXIMUM_POOL_SIZE
to be as big as you're likely to need. If you want to go unbounded, use the zero-argument LinkedBlockingQueue
constructor instead of the one being presently used. AFAICT, the rest of the code probably stays the same.
这篇关于简单的线程管理 - Java - Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!