是的,Java的ThreadPoolExecutor
允許你自定義線程工廠。你可以通過實現ThreadFactory
接口并重寫newThread(Runnable r)
方法來實現自定義線程工廠。然后,將這個自定義線程工廠傳遞給ThreadPoolExecutor
的構造函數。
以下是一個簡單的示例:
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CustomThreadPoolExecutor {
public static void main(String[] args) {
// 創建一個自定義線程工廠
ThreadFactory customThreadFactory = new ThreadFactory() {
private final ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();
private final AtomicInteger threadNumber = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
// 自定義線程名稱
Thread t = defaultThreadFactory.newThread(r);
t.setName("CustomThread-" + threadNumber.getAndIncrement());
return t;
}
};
// 使用自定義線程工廠創建一個線程池
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
5, 10, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(20), customThreadFactory);
// 提交任務到線程池
for (int i = 0; i < 30; i++) {
threadPoolExecutor.submit(() -> {
System.out.println("Task executed by thread: " + Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
// 關閉線程池
threadPoolExecutor.shutdown();
}
}
在這個示例中,我們創建了一個自定義線程工廠,它為每個新創建的線程設置了一個自定義名稱。然后,我們使用這個自定義線程工廠創建了一個ThreadPoolExecutor
實例,并提交了一些任務到線程池。