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 是以队列的方式一个一个被顺序执行的,所以执行的时间有可能和预期的时间不一致,因为前面的任务有可能消耗的时间较长,则后面的任务运行的时间也会被延后。

  • 相关阅读:
    MVC总结
    Python在Linux | Windows中输出带颜色的文字的方法
    flushdns
    linux配置java环境变量(详细)
    ELK
    sed 时间段
    如何让root用户能直接进行ssh登录?
    rsync有两种常用的认证方式,另外一种则是ssh。
    windows rsync server
    awk
  • 原文地址:https://www.cnblogs.com/newlangwen/p/8124965.html
Copyright © 2011-2022 走看看