我正在尝试将名称设置为线程,但ExecutorService设置自己的名称(如pool-1-thread-1)。题 Naming threads and thread-pools of ExecutorService给出使用ThreadFactory的建议。 请你考虑这个解决方案,它足够安全吗?
public class Test {
private volatile String prName;
private volatile boolean prIsDaemon;
private final ExecutorService pool = Executors.newCachedThreadPool(
(Runnable r) -> {
final Thread t = new Thread( r, prName );
t.setDaemon( prIsDaemon );
return t;
}
);
public void Submit(boolean daemon, String name, Runnable run) {
prIsDaemon = daemon;
prName = name;
pool.submit( run );
}
public void Shutdown() {
pool.shutdown();
}
public static void main(String[] args) {
final Test test = new Test();
final Runnable r = () -> {
System.out.println( Thread.currentThread().getName() );
};
test.Submit( false, "aaa", r );
test.Submit( false, "bbb", r );
test.Shutdown();
}
}
结果:
aaa
bbb