Java Threading - The Executor Framework: Defining Threads in Java
Java Threading - The Executor Framework: Defining Threads in Java
The main goal of this article is to present the better mechanism of executing threads in
Java and to show that working directly with threads is no longer necessary. Thanks to
the Executor framework, working with threads in Java is easier. And there are people
who claim that working with threads in Java is easier than in most other languages.
Let’s look at the example of defining a thread by implementing the Runnable interface:
To have the above code run by a separate thread the new java.lang.Thread object must
be instantiated and started as it is shown below:
Let’s take a look at the simple example of using the Executor framework to run
previously created task using fixed thread pool:
In the above example I used the ExecutorService interface which is an Executor that
provides a number of useful methods to control the task execution. For creation of the
concrete ExecutorService I used the Executors class and one of its static factory
methods: newFixedThreadPool(). Please refer to Executor API [ExecutorAPI].
Task scheduling
Summary
The article barely scratched the surface of the Executor framework. Thus, I encourage
the reader to study the framework’s documentation to see its power and simplicity.