Executor accepting wire as input

advertisements

I recently started exploring Java Executor framework. All executors are designed to accept Runnable or Callable. Why executors does not accept Thread as an input?


When talking about concurrency, it is very important to always distinguish between threads and tasks.

  • A task is just a piece of work that should be done - often represented as Runnable (or Callable in case a task produces a result).

  • A thread is a mechanism that enables tasks to be executed in parallel.

An Executor or ExecutorService is a facility that is able to execute tasks. Depending on the implementation, this executor may be able to execute multiple tasks in parallel - usually by using threads internally.

So if you are using an Executor or ExecutorService, you hand over tasks, hence Runnables for execution and let the executor manage its threads for you.

Note: As java.lang.Thread implements Runnable, it is possible to instantiate a Thread and pass it to execute(...). That's a very bad thing as the executor will just invoke the run() method of the thread as if it were a task, and does not start the thread. It is not thought to be used this way - if you see this somewhere: It's wrong!