定时器Timer

2018-10-28  本文已影响0人  笑才

1、Timer

public class test06 {
    public static void main(String[] args) throws InterruptedException {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask(){
            @Override
            public void run() {
                int i = 0;
                while(i<10){
                    i++;
                    try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}
                    System.out.println("线程名1:"+Thread.currentThread().getName());
                }
            }
        };
        TimerTask timerTask2 = new TimerTask(){
            @Override
            public void run() {
                int i = 0;
                while(i<10){
                    i++;
                    try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}
                    System.out.println("线程名2:"+Thread.currentThread().getName());
                }
            }
        };
            //timer.schedule(timerTask, 1000, 2000);
            timer.schedule(timerTask, 1000);
            timer.schedule(timerTask2, 1000);
            timer.schedule(new MyTimerTask(), 1000);
            Thread.sleep(5000);
            timer.cancel();
    }
}

class MyTimerTask extends TimerTask{
    @Override
    public void run() {
        int i = 0;
        while(i<10){
            i++;
            try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}
            System.out.println("线程名3:"+Thread.currentThread().getName());
        }
    }   
}
上一篇 下一篇

猜你喜欢

热点阅读