When should we use Java's Thread over Executor?

后端 未结 7 1224
一个人的身影
一个人的身影 2020-11-29 23:12

Executor seems like a clean abstraction. When would you want to use Thread directly rather than rely on the more robust executor?

7条回答
  •  情歌与酒
    2020-11-29 23:26

    It's always better to prefer Executor to Thread even for single thread as below

    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
    

    You can use Thread over Executor in below scenarios

    1. Your application needs limited thread(s) and business logic is simple

    2. If simple multi-threading model caters your requirement without Thread Pool

    3. You are confident of managing thread(s) life cycle + exception handling scenarios with help of low level APIs in below areas : Inter thread communication, Exception handling, reincarnation of threads due to unexpected errors

    and one last point

    1. If your application does not need customization of various features of ThreadPoolExecutor

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

    In all other cases, you can go for ThreadPoolExecutor

提交回复
热议问题