When should we use Java's Thread over Executor?

后端 未结 7 1195
一个人的身影
一个人的身影 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:31

    I use Thread when I need some pull based message processing. E.g. a Queue is take()-en in a loop in a separate thread. For example, you wrap a queue in an expensive context - lets say a JDBC connection, JMS connection, files to process from single disk, etc.

    Before I get cursed, do you have some scenario?

    Edit:

    As stated by others, the Executor (ExecutorService) interface has more potential, as you can use the Executors to select a behavior: scheduled, prioritized, cached etc. in Java 5+ or a j.u.c backport for Java 1.4.

    The executor framework has protection against crashed runnables and automatically re-create worker threads. One drawback in my opinion, that you have to explicitly shutdown() and awaitTermination() them before you exit your application - which is not so easy in GUI apps. If you use bounded queues you need to specify a RejectedExecutionHandler or the new runnables get thrown away.

    You might have a look at Brian Goetz et al: Java Concurrency in Practice (2006)

    0 讨论(0)
提交回复
热议问题