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

标签 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。这段代码工作正常

最佳答案

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

}

关于java - 为什么我的线程不能使用 Java ExecutorService 并行运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21102759/

相关文章:

java - 在 Visual VM 中限制分析

Java:如何在 Swing 中进行双缓冲?

c# - 我们可以在 TPL 中按名称或 ID 读取正在运行的任务数吗?

ruby - 使用 .each/iterator 的线程安全 Ruby 队列

java - 多个线程尝试以毫秒为键进行写入,但在 ConcurrentHashMap 中创建的不是一个键,而是许多键

java - 使用java swing表更新MySQL数据库值

JAVA:覆盖接口(interface)方法

c# - 如何在 C# 中从工作线程发布 UI 消息

java - 由于数据量巨大,AsyncTask 出现异常

java - Java比较和交换语义和性能