在我们以前使用ansyncTask去执行网络下载的时候,什么问题都没有,但是异步任务就是不执行。
原因:我们的线程使用完了。没有多余的线程可供使用了。
Execute和executeOnExecutor的区别。
Execute方法是串行执行(下载),而executeOnExecutor方法是并行执行。
串行的即必须等第一个下载完成后才能下载第二个。并行的是所以任务可以同步进行。
解决方法:使用executeOnExecutor()方法
当我们使用executeOnExecutor(Executor exec,Params... params)里面需要传入一个线程池。我们创建线程池可以创建一个无界线程池。
public class ThreadUtil {
private static ThreadPoolExecutor threadPoolExecutor;
/**
* 获取线程池单例*/
public static ThreadPoolExecutor getThreadPoolExecutor() {if (threadPoolExecutor == null) {
synchronized (ThreadUtil.class) {
if (threadPoolExecutor == null) {
//创建无界线程池,可以进行自动线程回收
threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
}
}
}
return threadPoolExecutor;
}
}
然后通过new XX().executeOnExecutor(ThreadUtil.getThreadPoolExecutor());这样就可以解决线程不够用的情况了。