Java Thread How to - Use Scheduled Thread Pool Executor








Question

We would like to know how to use Scheduled Thread Pool Executor.

Answer

/* ww w .ja  v a2 s .  c o m*/
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {

  public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter
        .ofPattern("yyyy-MM-dd HH:mm:ss");

    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(
        2);
    scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {

      throw new RuntimeException(
          " scheduleAtFixedRate test ScheduledThreadPoolExecutor");
    }, 0, 3000, TimeUnit.MILLISECONDS);

    scheduledThreadPoolExecutor.scheduleAtFixedRate(
        () -> {

          System.out.println("scheduleAtFixedRate: "
              + LocalDateTime.now().format(formatter));
        }, 0, 2000, TimeUnit.MILLISECONDS);

    scheduledThreadPoolExecutor.schedule(() -> {

      System.out.println("schedule");
    }, 1, TimeUnit.SECONDS);
  }

}

The code above generates the following result.