使用线程池时这样的一个crash:
03-16 00:13:08.904: E/AndroidRuntime(12261): java.util.concurrent.RejectedExecutionException: Task com.example.testfile.MainActivity$4$1@414e6fe8 rejected from java.util.concurrent.ThreadPoolExecutor@414e7360[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]03-16 00:13:08.904: E/AndroidRuntime(12261): at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1979)03-16 00:13:08.904: E/AndroidRuntime(12261): at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:786)03-16 00:13:08.904: E/AndroidRuntime(12261): at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1307)
原因:
线程池溢出时默认使用AbortPolicy,我们看下AbortPolicy实现
public static class AbortPolicy implements RejectedExecutionHandler {
/**
* Creates an {@code AbortPolicy}.
*/
public AbortPolicy() { }
/**
* Always throws RejectedExecutionException.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
可以看到添加到线程池的请求被拒绝时,抛出了个异常
解决方法:
设置新的拒绝策略,比如使用DiscardOldestPolicy,这个选择抛弃在队尾的请求,然后重新添加被拒请求:
mThreadPool = new ThreadPoolExecutor(mThreadCapacity, mThreadCapacity, 30, TimeUnit.SECONDS, queue, new DiscardOldestPolicy());
当然你也可以选择其它拒绝策略或自定义拒绝策略