线程池使用的好处:
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()