new Thread(task).start() VS ThreadPoolExecutor.submit(task) in Android

后端 未结 3 1972
情歌与酒
情歌与酒 2020-12-31 05:14

In my Android project I had a lot of places where I need to run some code asynchronously (a web request, call to db etc.). This is not long running tasks (maximum a few seco

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 05:48

    Based on the comment of Ordous I have modified my code to work with only one pool.

    public class App extends Application {
    
        private ThreadPoolExecutor mPool;
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            mPool =  new ThreadPoolExecutor(5, Integer.MAX_VALUE, 1, TimeUnit.MINUTES, new SynchronousQueue());
        }
    }
    
    
    public void submitRunnableTask(Runnable task){
        if(!mPool.isShutdown() && mPool.getActiveCount() != mPool.getMaximumPoolSize()){
            mPool.submit(task);
        } else {
            new Thread(task).start(); // Actually this should never happen, just in case...
        }
    }
    

    So, I hope this can be useful to someone else, and if more experienced people have some comments on my approach, I will very appreciate their comments.

提交回复
热议问题