Hemlata Hemlata - 2 months ago 10
Java Question

Why FixedThreadPool not working properly

Here's my following code:

ExecutorService executor = Executors.newFixedThreadPool(5);

executor.submit(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Start"+" "+Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End!"+" "+Thread.currentThread().getName());
}
}
});

executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);


Here's my output:

Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1


My understanding is that in my code there're
5
threads in
FixedThreadPool
. So when I run my code, it's supposed to output all
5
threads, right? Or Am I misunderstanding something?

In my output
thread-1
starts and end everytime but isn't it supposed to output all
5
threads when it loops in
for
loop?
Cause if only 1
thread
is doing the
task
then why do we even need 5
threads
?
Is there any way all
5
threads can output on the console?(I'm a newbie)

Answer

You are posting only one Runnable so your ExecutorService runs one task. It will use only one thread. To use multiple threads you must call submit multiple times or you can call invokeAll with a Collection of runnables.

EDIT

Something like this:

public void test() {
    int numberOfThreads = 5;
    ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
    for(int i=0; i<numberOfThreads; i++){
        executorService.submit(createRunnable());
    }
}

private Runnable createRunnable() {
    return new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println("Start" + "  " + Thread.currentThread().getName());
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("End!" + "  " + Thread.currentThread().getName());
            }
        }
    };
}