最近接触到了阿里的Android studio 的一个插件 aliCheck,一扫描尽然大几千个ERR,就连前面使用的lib 库里面也是大片爆红。
下面简单说下线程池的创建和使用:
*线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,
规避资源耗尽的风险。 说明:Executors各个方法的弊端:
1)newFixedThreadPool和newSingleThreadExecutor:
主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至OOM。(队列任务可能超过1000 甚至n)
2)newCachedThreadPool和newScheduledThreadPool:
主要问题是线程数最大数是Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至OOM。
那么怎样创建?
下面给出一个简单的栗子:
class BasicThreadFactory implements ThreadFactory {
private AtomicLong mThreadCounter;
/**
* 包装工厂
*/
private ThreadFactory mThreadFactory;
/**
* 非捕获异常处理器
*/
private Thread.UncaughtExceptionHandler mExceptionHandler;
/**
* 命名模式
*/
private String mNamingPattern;
/**
* 优先级
*/
private Integer mPriority;
/**
* 后台状态标识
*/
private Boolean mDaemonFlag;
public BasicThreadFactory(ThreadBuilder threadBuilder) {
if (threadBuilder instanceof DefaultThreadBuilder) {
DefaultThreadBuilder builder = (DefaultThreadBuilder) threadBuilder;
if (builder.mThreadFactory == null) {
mThreadFactory = Executors.defaultThreadFactory();
} else {
mThreadFactory = builder.mThreadFactory;
}
mNamingPattern = builder.mNamingPattern;
mDaemonFlag = builder.mDaemonFlag;
mExceptionHandler = builder.mExceptionHandler;
mPriority = builder.mPriority;
mThreadCounter = new AtomicLong();
}
}
@Override
public Thread newThread(@NonNull Runnable runnable) {
Thread thread = getWrappedFactory().newThread(runnable);
initThread(thread);
return thread;
}
private void initThread(Thread thread) {
if (getNamingPattern() != null) {
Long count = mThreadCounter.incrementAndGet();
thread.setName(String.format(getNamingPattern(), count));
}
if (getUncaughtExceptionHandler() != null) {
thread.setUncaughtExceptionHandler(getUncaughtExceptionHandler());
}
if (getPriority() != null) {
thread.setPriority(getPriority());
}
if (getDaemonFlag() != null) {
thread.setDaemon(getDaemonFlag());
}
}
/**
* 获取包装工厂
*
* @return 不会返回null
*/
public final ThreadFactory getWrappedFactory() {
return mThreadFactory;
}
/**
* 获取命名模式
*
* @return
*/
public final String getNamingPattern() {
return mNamingPattern;
}
/**
* 获取是否为后台线程标识
*
* @return
*/
public final Boolean getDaemonFlag() {
return mDaemonFlag;
}
/**
* 获取优先级
*
* @return
*/
public final Integer getPriority() {
return mPriority;
}
/**
* 获取非捕获异常处理器
*
* @return
*/
public final Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
return mExceptionHandler;
}
/**
* 获取创建的线程数量
*
* @return
*/
public long getThreadCount() {
return mThreadCounter.get();
}
pub

本文详细探讨了线程池的创建与使用方法,强调避免使用Executors,而推荐使用ThreadPoolExecutor来创建线程池,以降低内存溢出风险。文中还提供了一个具体的线程池实现案例。

1602

被折叠的 条评论
为什么被折叠?



