Confused on Java ThreadPool

后端 未结 2 522
误落风尘
误落风尘 2021-01-23 17:30

It is my first time to use Java Thread Pool for my new project, after I came across this link http://www.javacodegeeks.com/2013/01/java-thread-pool-example-using-executors-and-t

2条回答
  •  抹茶落季
    2021-01-23 18:02

    Bad example! The class called WorkerThread is not a thread, it is a "task".

    The threads are hidden inside the ExecutorService. The example creates an ExecutorService with five "worker" threads, it creates ten tasks, it asks the executor service to "perform" them, and then finally, it waits for all of the tasks to be completed. It's totally up to the ExecutorService to decide how and when and in which worker thread to perform each task.

    Another lesser problem with the example is how the main thread waits after asking the executor service to shut down. It spins, using CPU resources that maybe could have been used by one or more of the workers (depends on how many CPUs the host has available to run the various threads.) The wait loop should call Thread.yield() which gives up the main thread's time slice to any other runnable thread each time it is called.

提交回复
热议问题