Why don't my threads work in parallel using Java ExecutorService?

public class Test { private ExecutorService executor = Executors.newFixedThreadPool(50); public void startTenThreads() { for (int i = 0; i < 10; i++) { executor.execute(new FooWorker(i)); } } private final class FooWorker implements Runnable { private int threadNum; public FooWorker(int threadNum) { this.threadNum = threadNum; } public void run() { System.out.println("Thread " + threadNum + " starting"); Thread.sleep(60000); System.out.println("Thread " + threadNum + " finished"); } } } 

I want these threads to run in parallel, but the output shows that it does not work in parallel, but in sequence:

 Thread 1 starting Thread 1 finished Thread 2 starting Thread 2 finished Thread 3 starting Thread 3 finished Thread 4 starting Thread 4 finished Thread 5 starting Thread 5 finished ... 

What am I doing wrong?

EDIT: Found a problem, someone set the thread pool size to 1. This snippet code works fine

+6
source share
1 answer

Your code, as written, does not compile. I assume that you have something else in the code that you did not cut and paste here. Here is your code written for compilation. I tested it and it works for me. What is the difference between your actual code and the code below? (Please excuse the typo in "TheadTest".)

 import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TheadTest { private ExecutorService executor = Executors.newFixedThreadPool(50); public void startTenThreads() { for (int i = 0; i < 10; i++) { executor.execute(new FooWorker(i)); } } private final class FooWorker implements Runnable { private int threadNum; public FooWorker(int threadNum) { this.threadNum = threadNum; } public void run() { try { System.out.println("Thread " + threadNum + " starting"); Thread.sleep(60000); System.out.println("Thread " + threadNum + " finished"); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { TheadTest tt = new TheadTest(); tt.startTenThreads(); } } 
+1
source

All Articles