简体   繁体   中英

Executors NewFixedThreadPool not giving the expected result

I am trying to execute multiple threads in scala and for a simple test I run this code:

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.

Can someone explain me this phenomena?

The reason it hangs is that you don't shut down the ExecutorService . In Java (sorry, not familiar with Scala):

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

As to why you only see the message once: you create 20 threads, and give just one of them work. Threads won't do anything if you don't give them anything to do.

I think you assumed that this code would execute the runnable on each thread in the pool . That's simply not the case.

If you want to actually do this 20 times in different threads, you need to a) submit 20 runnables; b) synchronise the runnables in order that they actually need to run on separate threads:

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

The latch here ensures that the threads wait for each other before proceeding. Without it, the trivial work could easily be done on one thread before submitting another, so you wouldn't use all of the threads in the pool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM