Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do my threads not run 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, 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

like image 490
Popcorn Avatar asked Jan 13 '14 22:01

Popcorn


1 Answers

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();
    }

}
like image 188
lycono Avatar answered Nov 11 '22 08:11

lycono