ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -> { System.out.println("Task 1 executed"); }); executor.submit(() -> { System.out.println("Task 2 executed"); }); executor.shutdown();
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleAtFixedRate(() -> { System.out.println("Task executed every 5 seconds"); }, 0, 5, TimeUnit.SECONDS);In this example, we create a single-threaded scheduled executor service that executes a task every 5 seconds, starting immediately. The scheduleAtFixedRate() method schedules the task to run at a fixed interval. The TimeUnit.SECONDS parameter specifies the time unit of the interval. The executor service can be terminated using the shutdown() method.