首页 > 代码库 > 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简单介绍