AsyncTask简单介绍
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AsyncTask简单介绍相关的知识,希望对你有一定的参考价值。
AsyncTask = Handler + ThreadPoolExcutor 线程池
线程池:如果再来任务的话,队列中的容量放不下了,线程池就会重现创建一个线程处理新来的任务。
如果总线程数量超过128 就会出异常。
public class ThreadPoolTest { //线程池 private static final int CORE_POOL_SIZE = 5; private static final int MAXIMUM_POOL_SIZE = 10; private static final int KEEP_ALIVE = 1; private static final BlockingQueue<Runnable> sWorkQueue = new LinkedBlockingQueue<Runnable>(10); private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); public static void main(String[] args){ for (int i = 0; i < 21; i++) { sExecutor.execute(new MyTask()); } } private static final AtomicInteger taskCount = new AtomicInteger(1); static class MyTask implements Runnable{ //任务 int taskId = 0; public MyTask() { taskId = taskCount.getAndIncrement(); } @Override public void run() { int count = 1; while (count<5){ count++; try { Thread.sleep(3000); System.out.println(Thread.currentThread().getName()+"=执行="+taskId); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
以上是关于AsyncTask简单介绍的主要内容,如果未能解决你的问题,请参考以下文章
片段中的 Asynctask 未到达 onPostExecute
在 AsyncTask 中将新的 TextView 设置为片段
AsyncTask 和 FragmentManager 的问题
用 Asynctask 更新 FragmentTransaction 替换的片段