多线程 02 传统定时器技术回顾

(1)1秒以后炸

new Timer().schedule(new TimerTask() {

            @Override

            public void run() {

                System.out.println("bombing!!!");

            }

        }, 1000);

        while (true) {

            System.out.println(new Date().getSeconds());

            try {

                Thread.sleep(1000);

扫描二维码关注公众号,回复: 4485904 查看本文章

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

(2):10秒以后,然后每3秒炸一次。(timer是一个定时器,timerTask是一个任务。)

new Timer().schedule(new TimerTask() {

            @Override

            public void run() {

                System.out.println("bombing!!!");

            }

}, 10000,3000);

(3)子母弹的实现;每隔两秒炸一下。

class MyTimerTask extends TimerTask{

            @Override

            public void run() {

                System.out.println("bombing");

                new Timer().schedule(new MyTimerTask()

                ,2000);

            }

        }

        new Timer().schedule(new MyTimerTask(),2000);

(4)每隔多长时间炸

//每隔多长时间炸,交替着炸
class MyTimerTask extends TimerTask{
    @Override
    public void run() {
        count=(count+1)%2;
        System.out.println("bombing");
        new Timer().schedule(new MyTimerTask()
                ,2000+count*2000);
    }
}
//

如有疑问,请发邮件:[email protected]


github:  https://github.com/wangrui0/

猜你喜欢

转载自blog.csdn.net/qq_35524586/article/details/84972313
今日推荐