我的android应用程序中有一个ThreadPool,我在其中运行了一堆线程。
public class ThreadPoolExecuter {
private final ExecutorService mExecuter;
private static final int nThreads = 5;
private ThreadPoolExecuter() {
this.mExecuter = Executors.newFixedThreadPool(nThreads);
}
Java ThreadPool没有默认取消线程。我想到的一个解决方案是在提交runnable时保留Future的键值对。
public void add(Runnable runnable) {
Future<?> future = this.mExecuter.submit(runnable);
// Add future to my key-value pairs
if(Constant.DEBUG) Log.d(TAG, "Task submitted.");
}
然后有取消功能:
public boolean cancel(KEY) {
Future<?> future = map.get(KEY)
return future.cancel(mayInterruptIfRunning);
}
让我们说一个HashMap。价值是未来,关键是什么? 1)你的建议是什么?
Map<Key, Future<?>> map = new HashMap()<key, Future<?>>;
关于密钥,我考虑过为每个runnable传递一个id,如下所示:
2)您对此解决方案有何看法?
但我要提到的是,在我的runnable类中,有时候我遇到了InterruptedException。有什么方法可以避免吗?
class Runner implements Runnable {
private int id;
public Runner(int id) {
this.id = id;
}
@Override
public void run() {
System.out.println("Starting " + id);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("Crashed on:" + Thread.currentThread().getId());
}
System.out.println("ending " + id);
}
}
3)最后我想补充一下,在你的观点中,知道在java ThreadPool中开发取消函数的任何更好的解决方案对我来说很重要吗?
请注意,我没有寻找替代我的ThreadPool,例如Android中的AsyncTask,它具有默认取消功能。
答案 0 :(得分:1)
由于您的主要需求是能够立即取消所有正在运行的任务,因此您应该能够使用shutdownNow()
的{{1}}。默认ExecutorService
实现将调用ExecutorService
以中止正在运行的线程,因此您应该正确处理Thread.interrupt()
(通过关闭所使用的任何资源并退出该线程)。
答案 1 :(得分:0)
通常从线程外部取消线程本身包含一开始并不明显的各种风险。更安全的方法是在线程开始检查时查看是否仍然需要运行。