我目前正在开发一个在其主要布局中具有 ListView
的应用程序,它的项目是目录中包含的真实文件的包装器。
当列表被填充时,我执行一个 AsyncTask,它应该从 Properties
中检索一些数据。文件,如果未检索到此类数据,我将添加一个 Runnable
到 ThreadPoolExecutor
要从网站获取该数据,请将其保存到 Properties
中然后加载 Properties
.
如果我决定更改目录,List.clear()
在应用程序用新项目填充它之前执行。
因此,如果当前有工作/未决 Thread
在 ThreadPoolExecutor
里面,它们继续被执行并使我的应用程序崩溃,因为 List
中的项目不存在了。
我读过一些问题,但没有一个令我满意。如何防止当前 Activity Thread
s 访问列表并清空 ThreadPoolExecutor
的队列?或者,我如何设计一个可运行的,如果不再需要它,它不会干扰 List
?
更新:
在我重新填充 List
的方法中在执行 clear()
之前我做了以下操作:
if(mBlockingQueue.size()>0){
mBlockingQueue.drainTo(new ArrayList<Runnable>()); //I don't want to keep the workers
mThreadPoolExecutor.shutDownNow(); //This will execute .interrupt(); on the working Threads
}
更新 2: 这还不够:创建执行程序后使用以下内容
myThreadPoolExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r,ThreadPoolExecutor executor) {
//Do nothing
}
});
最佳答案
您可以使用此代码来获得暂停的任务列表:
BlockingQueue<Runnable> queue = threadPool.getQueue();
List<Runnable> list = new ArrayList<Runnable>();
int tasks = queue.drainTo(list);
然后你可以按照这个文档找到一种在 BlockingQueue 上使用 remove 的方法
关于java - 中断 ThreadPoolExecutor 当前线程并清空其队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21264345/