线程执行工具类

作者: AndroidXing | 来源:发表于2018-04-06 13:32 被阅读170次

    在Android中经常会用到多线程开发,最简单的做法是new一个Thread去执行,这种写法如果多的话,线程的创建和管理开销也是非常大的,在代码中lint也会有警告提示。现在介绍一个简洁的线程管理工具类。
    代码如下:

    
    import android.os.Handler;
    import android.os.Looper;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class TaskService {
    
        private static volatile TaskService sTaskService;
        private final ExecutorService mExecutorService;
        private final Handler mHandler;
    
    
        private TaskService(){
            mExecutorService = Executors.newCachedThreadPool();
            mHandler = new Handler(Looper.getMainLooper());
        }
    
        public static TaskService getInstance(){
            if(sTaskService==null){
                synchronized (TaskService.class){
                    if(sTaskService==null){
                        sTaskService = new TaskService();
                    }
                }
            }
            return sTaskService;
        }
    
        public void doBackTask(Runnable runnable){
            if(runnable!=null){
                mExecutorService.submit(runnable);
            }
        }
    
        public void doBackTaskDelay(final Runnable runnable, long delay){
            if(runnable!=null){
                if(delay<0){
                    delay = 0;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mExecutorService.submit(runnable);
                    }
                },delay);
            }
        }
    
        public void postTaskInMain(Runnable runnable){
            if(runnable!=null){
                mHandler.post(runnable);
            }
        }
    
        public Handler getHandler(){
            return mHandler;
        }
    }
    

    该工具类采用单例的实现方式,线程执行是用Executors.newCachedThreadPool()方式实现线程复用。
    使用方式:

    1. 开线程执行任务:
     TaskService.getInstance().doBackTask(new Runnable())
    
    1. 切换到主线程执行任务:
    TaskService.getInstance().postTaskInMain(new Runnable());
    
    1. 延时执行多线程任务:
    TaskService.getInstance().doBackTaskDelay(new Runnable(),3000);
    

    相关文章

      网友评论

        本文标题:线程执行工具类

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