一、背景:
在项目中,我们很多地方都会用到线程池,如果要是线程池异常
我们只能了解到线程池出现问题,但是不知道哪一个线程出现异常,数据表导入线程异常,邮件线程异常、短信功能异常等,很难直接找到问题所在。所以自定义线程就很有必要。
二、目的
看了背景,我们就知道为什么要自定义线程,为了更好的定位异常问题。
三、实现
1.编写属性类 ThreadPollConfig
定义一个线程Bean对象
@Configuration
public class ThreadPollConfig {
@Bean(name = "emailThread")
public ThreadPoolExecutor getEmailThreadPoll(){
//工厂对象
CustomNameThreadFactory mail = new CustomNameThreadFactory("mail");
return new ThreadPoolExecutor(20,50,5,
TimeUnit.SECONDS, new LinkedBlockingDeque<>(50),mail,
new ThreadPoolExecutor.DiscardPolicy());
}
}
2.编写一个工厂 实现线程工厂 ThreadFactory 重写方法newThread(),
这里其实并没有直接重写newThread(),只是通过 风方法CustomNameThreadFactory()
将变量进行修改
public class CustomNameThreadFactory implements ThreadFactory {
private final AtomicInteger poolNumber = new AtomicInteger();
private final ThreadGroup group;
private final String namePrefix;
private final AtomicInteger threadNumber = new AtomicInteger(0);
/**
* @param name 线程名
*/
public CustomNameThreadFactory(String name) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
if (!StringUtils.isNotBlank(name)) {
name = "pool ";
}
namePrefix = "pool" + "-" +
poolNumber.getAndIncrement() +
"-thread-";
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
3.结果展示
4.spring源码解析:
4.1.进入ThreadPoolExecutor
4.2.进入defaultThreadFactory
4.3.进入DefaultThreadFactory 查看spring如何定义线程