定时器的使用

参考

张孝祥系列


场景

Timer类的使用


实验

package cool.pengych.java.thread;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时器复习 :编写一个小程序轮流间隔2秒、4秒轰炸
 * 1、递归的使用
 * 2、循环取某个范围内的数字
 * @author pengyucheng
 */
public class TimerTest
{
	private int count = 1;
	class MyTimerTask extends TimerTask
	{
		@Override
		public void run()
		{
			count = (count + 1) % 2; // 注意这个小技巧的使用:循环取某个范围内的数字。num = (num + 1) % length
			System.out.println("bombing ... ");
			new Timer().schedule(new MyTimerTask(),2000+ 2000*count);
		}
	}
	
	public static void main(String[] args) 
	{
		/*第一:同一组特工bomb两次
		 * 2秒后第一次bomb,4秒后再bomb
		 */
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				
				System.out.println("bombing");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("bombing2");
			}
		},2000 );
		
		/*
		 * 第二、两组特工分布bomb一次
		 * 2秒后第一次bomb,4秒后再bomb
		 */
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				System.out.println("bombing");
				new Timer().schedule(new TimerTask() {
					@Override
					public void run() {
						System.out.println("bombing 2");
					}
				}, 4000);
			}
		},2000 );
		
		/*
		 * 第三、两组特工轮流bomb
		 */
		new Timer().schedule(new TimerTest().new MyTimerTask(), 1000);
		while(true)
		{
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			System.out.println(new Date().getSeconds());
		}
	}

}


你可能感兴趣的:(定时器的使用)