Problem:

How to execute threads using Java ExecutorService? Since Java 5 it’s the preferred way to run Threads. In the following example we’ll show how to do that.

Solution:

In previous posts (for example Java Thread Example) we’ve shown how to run tasks in separate threads manually. Well, that was cool 15 years ago :-) and in Java 5 have been replaced with java.util.concurrent that makes Thread related work much easier.

Here we’ll show Java ExecutorService example, which executes a couple of tasks at the same time. We’ll only implement a Runnable task and allow the executor to handle thread creation, starting, stopping, and reuse if needed (think how much you would need to implement to provide such functionality!):

In the above code we used Single Thread Pool Executor to execute tasks sequentially, which doesn’t matter much here and we’ll describe it in further posts.

What matters though is how to execute tasks using execute(Runnable) method and stopping the executor using shutdown() method. As an exercise run the example, but with executor.shutdown() commented out. :-)

As you can see the program waits for already submitted tasks to finish their work, even though the shutdown() method has been called. If you don’t want to wait for the tasks to finish you can call shutdownNow() method, which will try to stop the tasks immediately.

Here the result of running executor.shutdownNow():

Starting ExecutorService
Shutting down the executor
Number of not started: 4
The main thread ends now.
counter 1, value: 0

Shorter, no? :-)

What is also important here, the ExecutorService is created using static Factory method, which we can change to create executors with different characteristics, as we’ll show in the following posts. So stay tuned! :-)