多线程篇二:定时任务

1.定时任务定义:new一个定时器,定时器里面再new一个定时任务

new Timer().schedule(new TimerTask(){
    @Override
    public void run() {
        System.out.println("bombing!");
    }
},1000);//1S以后炸,之后每间隔2S炸一次。
View Code

 

2.设置定时炸弹:先炸2s、再炸4s、炸2s、炸4s。。。循环交替

package com.test.timerTask;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskTest {

    private static int count =0;
    public static void main(String[] args) {
        class MyTimerTask extends TimerTask{
            @Override
            public void run() {
                count =(count+1)%2;
                System.out.println("bombing!");
                new Timer().schedule(new MyTimerTask(), 2000+2000*count);
            }
        }
        
        new Timer().schedule(new MyTimerTask(), 2000);
        //秒钟计时
        while(true){
            System.out.println(new Date().getSeconds());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
View Code

 

posted @ 2016-10-13 21:10  陈小兵  阅读(619)  评论(0编辑  收藏  举报