java学习—— Timer执行定时任务



简单Timer使用实例, 

import java.util.TimerTask;

/**
 * timer演示
 */
public class TimerDemo {

	public static void main(String[] args) {
		
		System.out.println("currentThread id " + Thread.currentThread().getId());
		//创建一个定时器
		Timer timer = new Timer();
		//启动定时器 执行定时任务, 启动时间是1s后,每隔1s执行一次 
		timer.schedule(new RemindTask(), 1000 , 1000); 
		
		//timer.cancel(); //终止定时器
		
	}
	/**
	 * 继承TimerTask 定时任务 
	 */
	static class RemindTask extends TimerTask {
        public void run() {
        	System.out.println("currentThread id " + Thread.currentThread().getId());
            System.out.println("Time's up!");
            //timer.cancel(); //Terminate the timer thread
        }
    } 
}

Timer是线程安全的 。

测试结果 : 
currentThread id 1
currentThread id 8
Time's up!
currentThread id 8
Time's up!
currentThread id 8
Time's up!
currentThread id 8
Time's up!
currentThread id 8
Time's up!
currentThread id 8
Time's up!


简单Timer使用实例, 

import java.util.TimerTask;

/**
 * timer演示
 */
public class TimerDemo {

	public static void main(String[] args) {
		
		System.out.println("currentThread id " + Thread.currentThread().getId());
		//创建一个定时器
		Timer timer = new Timer();
		//启动定时器 执行定时任务, 启动时间是1s后,每隔1s执行一次 
		timer.schedule(new RemindTask(), 1000 , 1000); 
		
		//timer.cancel(); //终止定时器
		
	}
	/**
	 * 继承TimerTask 定时任务 
	 */
	static class RemindTask extends TimerTask {
        public void run() {
        	System.out.println("currentThread id " + Thread.currentThread().getId());
            System.out.println("Time's up!");
            //timer.cancel(); //Terminate the timer thread
        }
    } 
}

Timer是线程安全的 。

测试结果 : 
currentThread id 1
currentThread id 8
Time's up!
currentThread id 8
Time's up!
currentThread id 8
Time's up!
currentThread id 8
Time's up!
currentThread id 8
Time's up!
currentThread id 8
Time's up!


你可能感兴趣的:(java学习—— Timer执行定时任务)