Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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 1thread 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)
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.
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());
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.