多线程02-定时器

案例1

间隔1秒以后执行task任务

package org.lkl.timer;



import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;



public class TimerFoo {



    public static void main(String[] args) {

        

        TimerTask task = new TimerTask() {

            

            @Override

            public void run() {

                System.out.println("Liaokailin.");

            }

        };

        /**

         * 间隔1秒以后执行task任务

         */

        new Timer().schedule(task, 1000) ;

        

        while(true){

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

            try {

                Thread.sleep(1000) ;

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

    

}

 

案例2 

 间隔1秒以后第一次执行task ,随后间隔2秒执行一次task

package org.lkl.timer;



import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;



public class TimerFoo {



    public static void main(String[] args) {

        

        TimerTask task = new TimerTask() {

            

            @Override

            public void run() {

                System.out.println("Liaokailin.");

            }

        };

        /**

         * 间隔1秒以后第一次执行task ,随后间隔2秒执行一次task

         */

        new Timer().schedule(task, 1000,2000) ;

        

        /**

         * 用来计时,没间隔1秒输出当前时间对应的秒数

         */

        while(true){

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

            try {

                Thread.sleep(1000) ;

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

    

}

 

 

 案例3

间隔2秒以后执行一次task ,随后间隔4秒执行一次task

package org.lkl.timer;



import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;



public class TimerFoo {

    static int flag = 0 ;

    public static void main(String[] args) {

    

        class MyTimerTask extends TimerTask{

            int count = ++flag%2 ;

            //flag = flag%2 ;

            @Override

            public void run() {

                System.out.println("Liaokailin.");

                new Timer().schedule(new MyTimerTask() , 2000+2000*count) ;

            }

            

        }

        

     

        /**

         * 间隔2秒以后执行一次task ,随后间隔4秒执行一次task

         */

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

        

        /**

         * 用来计时,没间隔1秒输出当前时间对应的秒数

         */

        while(true){

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

            try {

                Thread.sleep(1000) ;

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

    

}

 

 

你可能感兴趣的:(多线程)