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

时间:2014-01-13 22:34:45

标签: java multithreading concurrency parallel-processing 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");
        }
    }
}

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

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
...

我做错了什么?

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

1 个答案:

答案 0 :(得分:1)

您编写的代码不会编译。我猜你在代码中还有其他东西在你没有剪切/粘贴的地方。这是你编写的代码。我测试了它,它对我有用。您的实际代码与下面的代码有什么区别? (请原谅#34; TheadTest&#34;中的拼写错误。)

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

}