面試場景模擬
面試官:小夥子平時開發中用過執行緒池嗎?聊一聊它
我:肯定用過啊,然後把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]