zoukankan      html  css  js  c++  java
  • 多线程-传统定时任务

    package com.thread.timer;
    
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    
    /**
     * 间隔2执行一次再隔4秒执行一次
     * 
     *
     */
    public class TraditionalTimerTest {
    
        public static void main(String[] args) throws InterruptedException {
            Timer timer = new Timer();
            long cur = System.currentTimeMillis();
            timer.schedule(new MyTimerTask(), 2000);
            while (true) {
                System.out.println(new Date().getSeconds());
                Thread.sleep(1000);
            }
        }
    
    }
    
    class MyTimerTask extends TimerTask {
        private static int count = 0;
    
        @Override
        public void run() {
            count = (count + 1) % 2;
            // TODO Auto-generated method stub
            System.out.println("bombing!!");
            
            new Timer().schedule(new MyTimerTask(), 2000+2000*count);
        }
    
    }

    Timer timer = new Timer();
    timer.schedule(new MyTimerTask(), 2000+2000*count);
    timer.schedule(new MyTimerTask(), 2000+2000*count);
    TimeTask 是以队列的方式一个一个被顺序执行的,所以执行的时间有可能和预期的时间不一致,因为前面的任务有可能消耗的时间较长,则后面的任务运行的时间也会被延后。

  • 相关阅读:
    Java基础01
    架构漫谈阅读笔记1
    机器学习-分类算法之k-近邻
    机器学习-模型选择
    机器学习-scikit-learn数据集
    机器学习-特征选择
    机器学习-数据的特征预处理
    实现模式阅读笔记二
    实现模式阅读笔记一
    《架构之美》阅读笔记七
  • 原文地址:https://www.cnblogs.com/newlangwen/p/8124965.html
Copyright © 2011-2022 走看看