In our previous blog, we talked mostly theroretical concepts about a ThreadPoolExecutor.
In this blog we will start with a ThreadPoolExecutor with a single thread.
What is a SingleThreadExecutor
- It has only a single thread available to execute the task, so can only execute one task at a time.
- The single thread executor is ideal for creating an event loop.
- Following attributes are set in a ThreadPoolExecutor for a single thread executor
- corePoolSize = 1
- maximumPoolSize = 1
- keepAliveTime = 0 milliseconds.
When would you need it
- When we want to run some task in other thread, but only one instance at a time
- E.g. some processing where order of execution matters, and we want to execute task2 only after task1 is completed.
Code Examples
For all our code examples – we will use this “dummy” Runnable class (MyDummyTask.java)
It does nothing, to be honest – just does a Thread.sleep for a second.

Executing a single task in a different thread
Here is the code to create a single thread executor service

On Executing it you will see an output like this

Executing multiple tasks one by one in a Single Thread Executor
We can also execute mutliple tasks on single thread executor service. It will just queue all the tasks and execute them in a sequential ordered way. Check the code example below

If you look at the output of the execution, you can see all tasks execute one by one – Task 1 after Task2, Task3 after Task2, and so on.

Code located at – SingleThreadExecutorDemo.java and MyDummyTask.java
In future blogs we will cover more different types of ThreadPoolExecutor, along with code examples
