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, however the output shows it is not running in parallel, but rather sequentially:
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 the problem, somebody had set the thread pool size to 1. This snippet code works fine
Your code as written doesn't compile. I'm guessing you have something else going on in code that you did not cut/paste here. Here is your code written to compile. 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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With