为什么使用Java ExecutorService时我的线程没有并行运行?

6
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。这段代码片段运行正常。


4
因为您的任务执行时间太短,以至于它们在下一次循环迭代之前就已经完成了。因此,您需要为线程提供更多的工作 - 例如随机休眠。同时还可以查看invokeAll方法。 - Boris the Spider
2
正如Boris the Spider所说,尝试使用以下代码:`public void run() { System.out.println("Thread " + threadNum + " starting"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread " + threadNum + " finished"); }`这对我很有效。 - upog
1
如果你只是像你那样添加sleep,它就无法编译。你能给我们实际的代码吗? - Peter Lawrey
嗯,谢谢你们的评论,你们是对的,这段代码片段运行得很好。我的实际代码中有一些问题导致它无法并行运行... - Popcorn
@Popcorn听起来像是你在某个地方使用了synchronized - Boris the Spider
显示剩余4条评论
1个回答

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

}

有很多不同之处,所以我不认为我能把它们全部粘贴出来。我仍在努力弄清楚这一点,但要点是我正在使用Apache HTTP客户端发送HTTP请求,并希望它们都并行运行。我认为这可能与使用HttpClient而不是AsyncHttpClient有关。仍在研究中。 - Popcorn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接