JAVA中定时器有哪几种写法呢?
下文笔者讲述java中定时器的三种写法分享,如下所示
Java定时器常见的三种写法
方式1: while循环一直运行 方式2: 借助Timer组件,循环运行 方式3: 使用线程池的方式运行定时器任务例:
创建一个thread 让它在while循环里一直运行着 通过sleep方法来达到定时任务的效果例
public class Task1 { public static void main(String[] args) { // run in a second // 每一秒钟执行一次 final long timeInterval = 1000; Runnable runnable = new Runnable() { public void run() { while (true) { // ------- code for task to run // ------- 要运行的任务代码 System.out.println("Hello, stranger"); // ------- ends here try { // sleep():同步延迟数据,并且会阻塞线程 Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } }; //创建定时器 Thread thread = new Thread(runnable); //开始执行 thread.start(); } }
方式2
使用Timer类调度任务 TimerTask则是通过在run()方法里实现具体任务 Timer实例可以调度多任务 它是线程安全 当Timer的构造器被调用时 创建一个线程 使用此线程调度任务
import java.util.Timer; import java.util.TimerTask; public class Task2 { public static void main(String[] args) { /** * Timer:是一个定时器工具,用来执行指定任务 * TimerTask:是一个抽象类,他的子类可以代表一个被Timer计划的任务 */ TimerTask task = new TimerTask() { @Override public void run() { // task to run goes here // 执行的输出的内容 System.out.println("Hello, stranger"); } }; Timer timer = new Timer(); // 定义开始等待时间 --- 等待 5 秒 // 1000ms = 1s long delay = 5000; // 定义每次执行的间隔时间 long intevalPeriod = 5 * 1000; // schedules the task to be run in an interval // 安排任务在一段时间内运行 timer.scheduleAtFixedRate(task, delay, intevalPeriod); } // end of main }
方式3:使用线程池的方式运行定时任务
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Task3 { public static void main(String[] args) { /** * Runnable:实现了Runnable接口,jdk就知道这个类是一个线程 */ Runnable runnable = new Runnable() { //创建 run 方法 public void run() { // task to run goes here System.out.println("Hello, stranger"); } }; // ScheduledExecutorService:是从Java SE5的java.util.concurrent里, // 做为并发工具类被引进的,这是最理想的定时任务实现方式。 ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间 // 10:秒 5:秒 // 第一次执行的时间为10秒,然后每隔五秒执行一次 service.scheduleAtFixedRate(runnable, 10, 5, TimeUnit.SECONDS); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。