美文网首页
Android ThreadPool、AsyncTask、Fut

Android ThreadPool、AsyncTask、Fut

作者: 图之 | 来源:发表于2020-02-17 15:58 被阅读0次

    使用多线程用new Thread():
    1.多任务情况下,避免线程频繁的创建销毁;
    2.多个线程频繁的创建会占用大量的资源,并且在资源竞争的时候出现问题,缺乏统一的管理,容易造成线程卡顿;
    3.多个线程频繁销毁,会频繁调用GC机制,降低性能并且耗时;
    线程池的作用:
    1.对线程统一管理,避免资源竞争造成卡顿、死机等问题;
    2.对线程服用,不会在线程结束后立即销毁,等待其他任务。避免了频繁创建、销毁和调用GC机制

    public class ThreadPool {
        ThreadPoolExecutor mThreadPoolExecutor;
    
        private int corePoolSize;
        private int maximumPoolSize;
        private long keepAliveTime;
    
        private static ThreadPool mThreadPool = null;
    
        public static ThreadPool getInstance() {
            if (mThreadPool == null) {
                synchronized (ThreadPool.class){
                    mThreadPool = new ThreadPool(5, 10, 5 * 1000);
                }
            }
            return mThreadPool;
        }
    
        private ThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
            this.corePoolSize = corePoolSize;
            this.maximumPoolSize = maximumPoolSize;
            this.keepAliveTime = keepAliveTime;
        }
    
        private ThreadPoolExecutor initExecutor() {
            if (mThreadPoolExecutor == null) {
                synchronized (ThreadPool.class) {
                    if (mThreadPoolExecutor == null) {
    
                        TimeUnit unit = TimeUnit.MILLISECONDS;
                        ThreadFactory threadFactory = Executors.defaultThreadFactory();
                        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
                        LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
    
                        mThreadPoolExecutor = new ThreadPoolExecutor(
                                corePoolSize,//核心线程数
                                maximumPoolSize,//最大线程数
                                keepAliveTime,//保持时间
                                unit,//保持时间对应的单位
                                workQueue,
                                threadFactory,//线程工厂
                                handler);//异常捕获器
                    }
                }
            }
            return mThreadPoolExecutor;
        }
    
    
        /**
         * 执行任务
         */
        public void executeTask(Runnable r) {
            initExecutor();
            mThreadPoolExecutor.execute(r);
        }
    
    
        /**
         * 提交任务
         */
        public Future<?> commitTask(Runnable r) {
            initExecutor();
            return mThreadPoolExecutor.submit(r);
        }
    
        /**
         * 删除任务
         */
        public void removeTask(Runnable r) {
            initExecutor();
            mThreadPoolExecutor.remove(r);
        }
    
    }
    
    

    FutureTask
    FutureTask是实现了future的Runable,FutureTask比Runable多了一个执行的返回值

     private void test(){
    
            AsyncTask<Boolean,String,Integer> asyncTask = new AsyncTask<Boolean, String, Integer>() {
    
                @Override
                protected Integer doInBackground(Boolean... booleans) {
                    return null;
                }
    
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                }
    
                @Override
                protected void onPostExecute(Integer integer) {
                    super.onPostExecute(integer);
                }
    
                @Override
                protected void onProgressUpdate(String... values) {
                    super.onProgressUpdate(values);
                }
    
                @Override
                protected void onCancelled(Integer integer) {
                    super.onCancelled(integer);
                }
    
                @Override
                protected void onCancelled() {
                    super.onCancelled();
                }
            };
            asyncTask.execute();
            asyncTask.getStatus();
    
            Callable<Boolean> callable = new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return false;
                }
            };
            FutureTask futureTask = new FutureTask(callable );
            futureTask.cancel(true);
    
            ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                    2,10,300,
                    TimeUnit.MICROSECONDS,new LinkedBlockingDeque<Runnable>(),
                    Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
            Future<Boolean> future= poolExecutor.submit(callable);
            future.cancel(true);
        }
    

    相关文章

      网友评论

          本文标题:Android ThreadPool、AsyncTask、Fut

          本文链接:https://www.haomeiwen.com/subject/riwbfhtx.html