type
Post
status
Published
slug
java/01
summary
Java定时任务调度的几种使用方式
tags
Java
category
笔记
password
这是我学习Java8笔记的一部分。在接下来的几分钟,你将会了解如何通过线程,任务(tasks)和 exector services来并行执行代码。
Timer
import lombok.extern.slf4j.Slf4j; import java.util.Timer; import java.util.TimerTask; @Slf4j public class MyTimer { public void timerTask() { // 通过 Timer 进行调度,支持按照固定频率或指定 Date 时刻执行。 // 所有的 TimerTask 是在同一个线程中串行执行,相互影响。 // schedule更加注重间隔时间,scheduleAtFixedRate更加注重频率 TimerTask timerTask1 = new TimerTask() { @Override public void run() { log.info("imerTask1 run ...", DateUtils.getTime()); FileStream fileStream = new FileStream(); fileStream.write("[" + DateUtils.getTime() + "]" + " timerTask1 run\n"); } }; TimerTask timerTask2 = new TimerTask() { @Override public void run() { log.info("timerTask2 run ...", DateUtils.getTime()); FileStream fileStream = new FileStream(); fileStream.write("[" + DateUtils.getTime() + "]" + " timerTask2 run\n"); } }; Timer timer = new Timer(); System.out.println(DateUtils.getTime()); FileStream fileStream = new FileStream(); fileStream.write("[" + DateUtils.getTime() + "]" + " timerTaskDemo start\n"); timer.schedule(timerTask1, 10); timer.schedule(timerTask2, 100); } }
Executor
import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @Slf4j public class MyExecutors { private static final int CORE_SIZE = 5; private static final ScheduledExecutorService executorService = java.util.concurrent.Executors.newScheduledThreadPool(CORE_SIZE); @SneakyThrows public static void executorsSchedule() { // 延迟1s后执行一次 executorService.schedule(() -> { String threadName = Thread.currentThread().getName(); System.out.println(threadName + ": exec schedule"); }, 1, TimeUnit.SECONDS); // 延迟1s后执行一次,支持返回值 Object res = executorService.schedule(() -> { String threadName = Thread.currentThread().getName(); return threadName + ": schedule finish"; }, 1, TimeUnit.SECONDS).get(); System.out.println("exec schedule return:" + res); int initialDelay = 0; int period = 1; // 按照固定频率执行,每隔2秒run一次 final ScheduledFuture<?> fixedHandle = executorService.scheduleAtFixedRate(() -> { String threadName = Thread.currentThread().getName(); System.out.println(threadName + ": exec fixedRate"); }, initialDelay, 2, TimeUnit.SECONDS); // 按照固定延时执行,上次执行完后隔2秒执行下一次 final ScheduledFuture<?> fixedDelayHandle = executorService.scheduleWithFixedDelay(() -> { String threadName = Thread.currentThread().getName(); System.out.println(threadName + ": exec fixedDelay"); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } }, initialDelay, 2, TimeUnit.SECONDS); String end = executorService.schedule(() -> { fixedHandle.cancel(true); fixedDelayHandle.cancel(true); return "end"; }, 60 * 1, TimeUnit.SECONDS).get(); System.out.println(end); } }
Thread 和 Runnable
所有的现代操作系统都通过进程和线程来支持并发。Java从JDK1.0开始执行线程。在开始一个新的线程之前,你必须指定由这个线程执行的代码,通常称为task。这可以通过实现
Runnable
——一个定义了一个无返回值无参数的run()
方法的函数接口,如下面的代码所示:Runnable task=()->{ String threadName= Thread.currentThread().getName(); System.out.println("Hello "+ threadName);}; task.run(); Thread thread=new Thread(task);thread.start(); System.out.println("Done!");