Reputation: 174
I am trying to display the name of the running threads in the run method. These threads are created in a fixed thread pool:
ExecutorService e = Executors.newFixedThreadPool(size);
The Java API doesn't help me, how can I do this?
Also, it'd be great to know how to customize the name of those threads in the pool.
Upvotes: 0
Views: 367
Reputation: 11996
Here's sample which answers both your questions:
ExecutorService es = Executors.newFixedThreadPool(4, new ThreadFactory() {
private final AtomicInteger counter = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "MyThread-" + counter.getAndIncrement());
}
});
es.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
ThreadFactory
is to the rescue! Note that threads aren't required to have unique names.
Upvotes: 2