kpagcha
kpagcha

Reputation: 174

How to get the name of a Thread in a Fixed Thread Pool

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

Answers (1)

Victor Sorokin
Victor Sorokin

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

Related Questions