面试场景模拟
面试官:小伙子平时开发中用过线程池吗?聊一聊它
我:肯定用过啊,然后把build的线程池十八问一顿巴拉巴拉
面试官:不错不错,挺了解的嘛,那你知道怎么给线程池命名?手写一个工厂类给线程池命名吧
我:啊这,现场手撕吗?面试官默默的递上A4...
如何给线程池命名?这是一个好问题,如果我们的项目模块较多,在运行时调用了不同模块的线程池,为了在发生异常后快速定位问题,我们一般会在构建线程池时给它一个名字,这里我们提供几种线程池命名的方法。
方法一: 通过Spring 框架提供的CustomizableThreadFactory命名ThreadFactory springThreadFactory = new CustomizableThreadFactory("Spring线程池:");
ExecutorService exec = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(10),springThreadFactory);
exec.submit(() -> {
log.info(exec.toString());
});
方法二: 通过Google guava工具类提供的ThreadFactoryBuilder命名
//链式调用
ThreadFactory guavaThreadFactory = new ThreadFactoryBuilder().setNameFormat("guava线程池:").build();
ExecutorService exec = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(10),guavaThreadFactory );
exec.submit(() -> {
log.info(exec.toString());
});
其实还有一个是Apache commons-lang3 提供的 BasicThreadFactory工厂类,也可以给线程池命名,咱这里就不贴代码了,原因是他们的本质都是通过Thread 的setName()方法实现的!所以,我们其实自己也可以设计一个工厂类也实现线程池的命名操作!
方法三: 自定义工厂类实现线程池命名先定义一个工厂类,通过实现ThreadFactory的newThread方法,完成命名。
public class MyThreadFactory implements ThreadFactory {
private final AtomicInteger threadNum = new AtomicInteger();
private final String name;
/**
* 创建一个带名字的线程池生产工厂
*/
public MyThreadFactory(String name) {
this.name = name;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName(name + "-" + threadNum.incrementAndGet());
return t;
}
}
调用一下看看结果:
@Slf4j
public class Test {
public static void main(String[] args) {
MyThreadFactory myThreadFactory = new MyThreadFactory("javaBuild-pool");
ExecutorService exec = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(10),myThreadFactory);
exec.submit(() -> {
log.info(exec.toString());
});
}
}
输出:
17:46:37.387 [javaBuild-pool-1] INFO com.javabuild.server.pojo.Test - java.util.concurrent.ThreadPoolExecutor@1ee7d6d6[Running, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]