为什么我的线程不能使用Java ExecutorService并行运行?

Pop*_*orn 6 java parallel-processing concurrency multithreading 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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望这些线程并行运行,但输出显示它不是并行运行,而是顺序运行:

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
...
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

编辑:发现问题,有人已将线程池大小设置为1.此代码段工作正常

lyc*_*ono 1

您编写的代码无法编译。我猜您的代码中还有其他事情没有在此处剪切/粘贴。这是您编写的用于编译的代码。我测试了它,它对我有用。你的实际代码和下面的代码有什么区别?(请原谅“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();
    }

}
Run Code Online (Sandbox Code Playgroud)