在使用 ThreadPoolExecutor 时,您可以通过实现 ThreadFactory 接口来设置线程的名称。ThreadFactory 是一个工厂接口,它的作用是创建线程,您可以通过重写它的 newThread 方法来设置线程的名称。
代码示例如下:
import java.util.concurrent.ThreadFactory;
public class NamedThreadFactory implements ThreadFactory {
private final String name;
public NamedThreadFactory(String name) {
this.name = name;
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName(name);
return t;
ThreadPoolExecutor executor = new ThreadPoolExecutor(
numThreads, // core pool size
numThreads, // maximum pool size
0L, // keep-alive time for idle threads
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
new NamedThreadFactory("MyThread"));
这样,您就可以在线程池中创建具有指定名称的线程了。