Executors newSingleThreadScheduledExecutor() Method Example

In this article, we will discuss Executors newSingleThreadScheduledExecutor() method with examples.

5. Executors.newSingleThreadScheduledExecutor() Method

This method creates a single-threaded executor that can schedule commands to run after a given delay or to execute periodically. (Note however that if this single thread terminates due to a failure during execution prior to the shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newScheduledThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
Syntax:
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

Executors.newSingleThreadScheduledExecutor() Method Example

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ExecutorsDemo {

    public static void main(String[] args) {
        ExecutorsDemo demo = new ExecutorsDemo();
        demo.newSingleThreadScheduledExecutor();
    }

    private void newSingleThreadScheduledExecutor() {
        System.out.println("Thread main started");

        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        // Create a task
        Runnable task1 = () -> {
            System.out.println("Executing the task1 at: " + new Date());
        };

        scheduledExecutorService.scheduleAtFixedRate(task1, 0, 2, TimeUnit.SECONDS);

        System.out.println("Thread main finished");
    }
}
Output:
Thread main started
Thread main finished
Executing the task1 at: Mon Sep 10 13:15:57 IST 2018
Executing the task1 at: Mon Sep 10 13:15:59 IST 2018
Executing the task1 at: Mon Sep 10 13:16:01 IST 2018
Executing the task1 at: Mon Sep 10 13:16:03 IST 2018
Executing the task1 at: Mon Sep 10 13:16:05 IST 2018
Executing the task1 at: Mon Sep 10 13:16:07 IST 2018
...............

Comments