首页 > 代码库 > AsyncTask简单介绍
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简单介绍
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。