Android线程池简单使用

线程池使用的好处:

1)对多个线程进行统一地管理,避免资源竞争中出现的问题。

2)对线程进行复用,线程在执行完任务后不会立刻销毁,而会等待另外的任务,这样就不会频繁地创建、销毁线程和调用GC。

使用ThreadPoolExecutor创建基本线程池,构造方法:

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}
//示例1
final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
    3, //核心线程数
    10, //最大线程数量
    60,// 空闲线程等待时间
    TimeUnit.SECONDS, //时间单位
    new ArrayBlockingQueue<Runnable>(100));
    
    Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    //... 耗时操作
                }
            };
    threadPoolExecutor.execute(runnable);
//示例2
private val cacheThread: ExecutorService by lazy { 
    ThreadPoolExecutor(
        Runtime.getRuntime().availableProcessors() * 30, 
        Runtime.getRuntime().availableProcessors() * 50,
        600L, 
        TimeUnit.SECONDS,
        SynchronousQueue<Runnable>()); }
//示例3
public class MyThreadFactory implements ThreadFactory {

    private int counter;
    private String name;

    public MyThreadFactory(String name) {
        counter = 0;
        this.name = name;
    }

    @Override
    public Thread newThread(Runnable run) {
        Thread thread = new Thread(run, name + "-Thread-" + counter);
        counter++;
        Timber.d("create thread with name: %s", thread.getName());
        return thread;
    }
}

public class MyExecutor extends ThreadPoolExecutor {

    public MyExecutor(String threadPrefix) {
        super(2, 6, 60,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(3),
                new MyThreadFactory(threadPrefix),
                new DiscardOldestPolicy()
        );
    }

    public static ThreadPoolExecutor polling = new MyExecutor("polling");

    public static ThreadPoolExecutor backgroundTask = new MyExecutor("backgroundTask");

}

以下是使用:

MyExecutor.polling.execute {
    doStatus()
}

MyExecutor.polling.execute {
    cleanDb()
}

MyExecutor.polling.shutdownNow()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值