定时器

package cn.itcast;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TraditionalTimerTest {

	private static int count = 0;
	public static void main(String[] args) {
		// 从程序运行10s之后,每隔3s打印一次bombing!
		new Timer().schedule(new TimerTask() {
			
			@Override
			public void run() {
				System.out.println("bombing!");
				
			}
		}, 10000, 3000);
		
		// 隔2s,4s交替打印bombing!
		class MyTimerTask extends TimerTask{
			
			@Override
			public void run() {
				count = (count + 1) % 2;
				System.out.println("bombing!");
				new Timer().schedule(/*new TimerTask() {
					
					@Override
					public void run() {
						System.out.println("bombing!");
					}
				}*/new MyTimerTask(),2000 + 2000*count);
			}
		}
		
		new Timer().schedule(new MyTimerTask(), 2000);
		
		// 打印时间用
		while(true){
			System.out.println(new Date().getSeconds());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

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