执行者 NewFixedThreadPool 没有给出预期的结果

Executors NewFixedThreadPool not giving the expected result

我正在尝试在 Scala 中执行多个线程,为了进行简单测试,我 运行 此代码:

Executors.newFixedThreadPool(20).execute( new Runnable {
      override def run(): Unit = {        
        println("Thread Started!")
      }
})

As far as I could understand, it would create 20 threads and call the print function, but this is not what's happening. It creates only one thread, executes the print and hangs.

谁能解释一下这个现象?

它挂起的原因是您没有关闭 ExecutorService。在Java(抱歉,不熟悉Scala):

ExecutorService executor = Executors.newFixedThreadPool(20); // or 1.
executor.execute(() -> System.out.println("..."));
executor.shutdown();

至于为什么你只看到一次消息:你创建了 20 个线程,并且只给其中一个线程工作。如果你不给它们任何事情做,线程将不会做任何事情。

我认为您假设此代码将在池 中的每个线程上执行运行nable 。根本不是这样。

如果你想在不同的线程中实际执行 20 次,你需要 a) 提交 20 运行nables; b) 同步 运行nables 以便它们实际需要 运行 在单独的线程上:

CountdownLatch latch = new CountdownLatch(1);
ExecutorService executor = Executors.newFixedThreadPool(20);
for (int i = 0; i < 20; ++i) {
  executor.execute(() -> {
    latch.await();  // exception handling omitted for clarity.
    System.out.println("...");
  });
}
latch.countdown();
executor.shutdown();

这里的闩锁确保线程在继续之前相互等待。没有它,在提交另一个线程之前可以很容易地在一个线程上完成琐碎的工作,因此您不会使用池中的所有线程。