Using our ThreadFactory in an Executor object
In the previous recipe, we introduced the factory pattern and provided an example of how to implement a factory of threads implementing the ThreadFactory
interface.
The Executor framework is a mechanism that allows you to separate thread creation and its execution. It's based on the Executor
and ExecutorService
interfaces and the ThreadPoolExecutor
class that implements both these interfaces. It has an internal pool of threads and provides methods that allow you to send two kinds of tasks to execute them in the pooled threads. These two kinds of tasks are as follows:
- Classes that implement the
Runnable
interface, to implement tasks that don't return a result - Classes that implement the
Callable
interface, to implement tasks that return a result
Internally, the Executor
framework uses a ThreadFactory
interface to create threads that it uses to generate new threads. In this recipe, you will learn how to implement your own thread class, a thread factory...