Android开发中,线程池工具类的封装与使用。

一、线程池工具类

/**

* 线程池工具类

* @author zhangjikai

* 20190711

*/

public class ThreadPoolUtil {

//核心线程数为5

    private static int CORE_POOL_SIZE=5;

//线程池最大线程数

    private static int MAX_POOL_SIZE=20;

//额外线程空状态生存时间

    private static int KEEP_ALIVE_TIME=10000;

//阻塞队列。当核心线程都被占用,且阻塞队列已满的情况下,才会开启额外线程。

    private static BlockingQueueblockingQueue=new ArrayBlockingQueue(10);

//线程池

    private static ThreadPoolExecutorthreadPool;

//无参构造方法

    public ThreadPoolUtil() {

}

//线程工厂

    private static ThreadFactorythreadFactory=new ThreadFactory() {

private final AtomicIntegerinteger=new AtomicInteger();

@Override

        public Thread newThread(Runnable runnable) {

return new Thread(runnable,"myThreadPool thread:" +integer.getAndIncrement());

}

};

//静态代码块

    static {

threadPool=new ThreadPoolExecutor(CORE_POOL_SIZE,MAX_POOL_SIZE,KEEP_ALIVE_TIME,TimeUnit.SECONDS,blockingQueue,threadFactory);

}

public static void execute(Runnable runnable) {

threadPool.execute(runnable);

}

public static void execute(FutureTask futureTask) {

threadPool.execute(futureTask);

}

public static void cancel(FutureTask futureTask) {

futureTask.cancel(true);

}

}

二、使用

private void testPool(){

ThreadPoolUtil.execute(new Runnable() {

@Override

        public void run() {

/**

* 这里写你需要执行的操作

*/

        }

});

}

你可能感兴趣的:(Android开发中,线程池工具类的封装与使用。)