Android thread pool management tools

Transfer from Android thread pool

public class AppExecutors {
    private static final String TAG = "AppExecutors";
    /**磁盘IO线程池**/
    private final ExecutorService diskIO;
	/**网络IO线程池**/
    private final ExecutorService networkIO;
	/**UI线程**/
    private final Executor mainThread;
	/**定时任务线程池**/
    private final ScheduledExecutorService scheduledExecutor;

    private volatile static AppExecutors appExecutors;

    public static AppExecutors getInstance() {
        if (appExecutors == null) {
            synchronized (AppExecutors.class) {
                if (appExecutors == null) {
                    appExecutors = new AppExecutors();
                }
            }
        }
        return appExecutors;
    }

    public AppExecutors(ExecutorService diskIO, ExecutorService networkIO, Executor mainThread, ScheduledExecutorService scheduledExecutor) {
        this.diskIO = diskIO;
        this.networkIO = networkIO;
        this.mainThread = mainThread;
        this.scheduledExecutor = scheduledExecutor;
    }

    public AppExecutors() {
        this(diskIoExecutor(), networkExecutor(), new MainThreadExecutor(), scheduledThreadPoolExecutor());
    }
	/**
	 * 定时(延时)任务线程池
	 * 
	 * 替代Timer,执行定时任务,延时任务
	 */
    public ScheduledExecutorService scheduledExecutor() {
        return scheduledExecutor;
    }

	/**
	 * 磁盘IO线程池(单线程)
	 * 
	 * 和磁盘操作有关的进行使用此线程(如读写数据库,读写文件)
	 * 禁止延迟,避免等待
	 * 此线程不用考虑同步问题 
 	 */
    public ExecutorService diskIO() {
        return diskIO;
    }
	/**
	 * 网络IO线程池
	 * 
	 * 网络请求,异步任务等适用此线程
	 * 不建议在这个线程 sleep 或者 wait  
	 */
    public ExecutorService networkIO() {
        return networkIO;
    }

	/**
	 * UI线程
	 * 
	 * Android 的MainThread
	 * UI线程不能做的事情这个都不能做
	 */
    public Executor mainThread() {
        return mainThread;
    }

    private static ScheduledExecutorService scheduledThreadPoolExecutor() {
        return new ScheduledThreadPoolExecutor(16, r -> new Thread(r, "scheduled_executor"), (r, executor) -> Log.e(TAG, "rejectedExecution: scheduled executor queue overflow"));
    }

    private static ExecutorService diskIoExecutor() {
        return new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), r -> new Thread(r, "disk_executor"), (r, executor) -> Log.e(TAG, "rejectedExecution: disk io executor queue overflow"));
    }

    private static ExecutorService networkExecutor() {
        return new ThreadPoolExecutor(3, 6, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(6), r -> new Thread(r, "network_executor"), (r, executor) -> Log.e(TAG, "rejectedExecution: network executor queue overflow"));
    }


    private static class MainThreadExecutor implements Executor {
        private final Handler mainThreadHandler = new Handler(Looper.getMainLooper());

        @Override
        public void execute(@NonNull Runnable command) {
            mainThreadHandler.post(command);
        }
    }
}


usage:

UI thread:

	AppExecutors.getInstance().mainThread().execute(new Runnable() {
            @Override
            public void run() {
                //do something
            }
        });

Disk IO thread pool

	AppExecutors.getInstance().diskIO().execute(new Runnable() {
            @Override
            public void run() {
                //do something
            }
        });

Network IO thread pool

	AppExecutors.getInstance().networkIO().execute(new Runnable() {
            @Override
            public void run() {
                //do something
            }
        });

Timing (delay) thread pool task

3 seconds delay after the implementation of:

AppExecutors.getInstance().scheduledExecutor().schedule(new Runnable() {
           @Override
           public void run() {
   			// do something
           }
       },3,TimeUnit.SECONDS);

5 seconds after the first start, executed every 3 seconds (first time start interval between 3 seconds and the second execution started)

AppExecutors.getInstance().scheduledExecutor().scheduleAtFixedRate(new Runnable() {
           @Override
           public void run() {
   			// do something
           }
       }, 5, 3, TimeUnit.MILLISECONDS);

5 seconds after the first start, executed every 3 seconds (first run to complete the interval between 3 seconds and the second start)

AppExecutors.getInstance().scheduledExecutor().scheduleWithFixedDelay(new Runnable() {
           @Override
           public void run() {
   			// do something
           }
       }, 5, 3, TimeUnit.MILLISECONDS);

Cancel the timer (delay) task

The above three methods will have one of the following return values:

ScheduledFuture<?> scheduledFuture;		 

Cancel the timer ( wait for the end of the current task, cancel the timer)

scheduledFuture.cancel(false);

Cancel the timer ( do not wait for the current mandate expires, cancel the timer)

scheduledFuture.cancel(true);

Of course, are double checked (double-check) singleton used above.

In my project, not using the Singleton pattern:
temporarily no problem

/**
 * Global executor pools for the whole application.
 * <p>
 * Grouping tasks like this avoids the effects of task starvation (e.g. disk reads don't wait behind
 * webservice requests).
 */
public class AppExecutors {

    private final Executor mDiskIO;

    private final Executor mNetworkIO;

    private final Executor mMainThread;
    private final ScheduledThreadPoolExecutor schedule;

    public AppExecutors() {
        this.mDiskIO = Executors.newSingleThreadExecutor();

        this.mNetworkIO = Executors.newFixedThreadPool(3);

        this.mMainThread = new MainThreadExecutor();

        this.schedule = new ScheduledThreadPoolExecutor(5, new ThreadPoolExecutor.AbortPolicy());
    }

    public Executor diskIO() {
        return mDiskIO;
    }

    public ScheduledThreadPoolExecutor schedule() {
        return schedule;
    }

    public Executor networkIO() {
        return mNetworkIO;
    }

    public Executor mainThread() {
        return mMainThread;
    }

    private static class MainThreadExecutor implements Executor {
        private Handler mainThreadHandler = new Handler(Looper.getMainLooper());

        @Override
        public void execute(@NonNull Runnable command) {
            mainThreadHandler.post(command);
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_43115440/article/details/90479752