ThreadFactory Named Worker Threads
Name pool threads through a ThreadFactory so thread dumps and logs identify workers: fixed pools spawn one named thread per task until core size.
Code
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class NamedWorkers {
public static void main(String[] args) throws InterruptedException {
AtomicInteger seq = new AtomicInteger();
// 自定义 ThreadFactory:池里每个线程都有可诊断的名字
ThreadFactory factory = task -> {
Thread t = new Thread(task, "billing-worker-" + seq.incrementAndGet());
t.setDaemon(true);
return t;
};
ConcurrentLinkedQueue<String> names = new ConcurrentLinkedQueue<>();
ExecutorService pool = Executors.newFixedThreadPool(2, factory);
pool.submit(() -> {
sleep(100);
names.add(Thread.currentThread().getName());
});
pool.submit(() -> {
sleep(100);
names.add(Thread.currentThread().getName());
});
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
// 两个任务各占一个线程:固定池按核心数依次创建命名线程
System.out.println("workers: " + names.stream().sorted().toList());
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}How it works
ThreadFactory Named Worker Threads comes down to the class NamedWorkers and the function sleep.
The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
Using it
The main signature reads static void sleep(long ms)
The demo output is labeled (workers:), so every printed line maps back to its originating operation.
Treat main as the orchestrator calling sleep in a fixed order.
Key statements
ExecutorService pool = Executors.newFixedThreadPool(2, factory);
Thread t = new Thread(task, "billing-worker-" + seq.incrementAndGet());
names.add(Thread.currentThread().getName());
Interactive Tools for This Topic
FAQ
- What does ThreadFactory Named Worker Threads print when run?
- Run it as a complete program — the output lines carry labels such as `workers:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.