转:定时器设计
程序员文章站
2022-04-04 16:49:08
...
1、传统的定时器实现
- package cn.itcast.thread;
- import java.util.Date;
- import java.util.Timer;
- import java.util.TimerTask;
- public class TraditionalTimer {
- private static int count = 0;
- public static void main(String[] args) {
- //延迟2秒执行run方法中的内容
- final Timer timer = new Timer();
- timer.schedule(new TimerTask() {
- public void run() {
- System.out.println("haha");
- }
- }, 2000);
- //延迟2秒执行run方法中的内容,以后每间隔一秒去执行run方法
- timer.schedule(
- new TimerTask() {
- public void run() {
- System.out.println("hello java");
- }
- },
- 2000,
- 1000);
- //延迟2秒执行run方法中的内容,以后根据count的值判断是间隔2秒还是4秒去执行run方法
- System.out.println(new Date().getSeconds());
- class MyTimerTask extends TimerTask {
- public void run() {
- count ++;
- System.out.println(new Date().getSeconds());
- System.out.println("hello java!");
- if (count % 2 == 1) {
- timer.schedule(new MyTimerTask(), 4000);
- } else {
- timer.schedule(new MyTimerTask(), 2000);
- }
- }
- }
- TimerTask tt = new MyTimerTask();
- timer.schedule(tt, 2000);
- }
- }
2、利用jdk新特性来设计定时器
- package cn.itcast.thread;
- import java.util.Calendar;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- public class ModernTimerTest {
- public static void main(String[] args) {
- final ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
- timer.schedule(
- new Runnable() {
- public void run() {
- System.out.println(Calendar.getInstance().get(Calendar.SECOND));
- }
- },
- 1,
- TimeUnit.SECONDS
- );
- class MyTask implements Runnable {
- public void run() {
- System.out.println(" ----> " + Calendar.getInstance().get(Calendar.SECOND));
- timer.schedule(new MyTask(), 2, TimeUnit.SECONDS);
- }
- }
- timer.schedule(
- new MyTask(),
- 1,
- TimeUnit.SECONDS
- );
- }
- }
上一篇: android检测退出
下一篇: 网红流沙手机壳 机场安检遇尴尬