How to implement simple threading with a fixed number of worker threads

后端 未结 7 880
渐次进展
渐次进展 2020-12-04 06:49

I\'m looking for the simplest, most straightforward way to implement the following:

  • The main program instantiates worker threads to do a task.
  • Only
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 07:38

    1. If your task queue is not going to be unbounded and tasks can complete in shorter time intervals, you can use Executors.newFixedThreadPool(n); as suggests by experts.

      The only drawback in this solution is unbounded task queue size. You don't have control over it. The huge pile-up in task queue will degrade performance of application and may cause out of memory in some scenarios.

    2. If you want to use ExecutorService and enable work stealing mechanism where idle worker threads share the work load from busy worker threads by stealing tasks in task queue. It will return ForkJoinPool type of Executor Service.

      public static ExecutorService newWorkStealingPool(int parallelism)

      Creates a thread pool that maintains enough threads to support the given parallelism level, and may use multiple queues to reduce contention. The parallelism level corresponds to the maximum number of threads actively engaged in, or available to engage in, task processing. The actual number of threads may grow and shrink dynamically. A work-stealing pool makes no guarantees about the order in which submitted tasks are executed.

    3. I prefer ThreadPoolExecutor due to flexibility in APIs to control many paratmeters, which controls the flow task execution.

      ThreadPoolExecutor(int corePoolSize, 
                             int maximumPoolSize, 
                             long keepAliveTime, 
                             TimeUnit unit, 
                             BlockingQueue workQueue, 
                             ThreadFactory threadFactory,
                             RejectedExecutionHandler handler)
      

    in your case, set both corePoolSize and maximumPoolSize as N. Here you can control task queue size, define your own custom thread factory and rejection handler policy.

    Have a look at related SE question to control the pool size dynamically:

    Dynamic Thread Pool

提交回复
热议问题