多線程_幾種定時器的寫法


1 :固定時間後執行一次任務:1000毫秒後執行任務(只執行一次)

2: 5000毫秒後,執行任務,以後每隔1000毫秒再執行一次任務(無限執行)

3:交替再生:任務24秒交替的執行(無限執行)

4: 創建兩個循環交替任務:2秒後,A任務執行。 A任務裏面創建一個B任務4秒後執行,B任務裏面又創建一個A任務2秒後執行,如此往復。


                1,2,3代碼:

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
 * @author Administrator @zsw 2012-7-19 下午04:37:19
 */
public class TraditionalTimer {
	public static void main(String[] args) {
		//1:
//		test1();
		
		//2:
//		test2();
		
		//3:
		test3();
        //用於打印時間秒數
		while (true) {
			System.out.println(new Date().getSeconds());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}

	//1:固定時間後執行一次任務:1000毫秒後執行任務(只執行一次)
	public static void test1() {
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.out.println("bombing!");
			}
		}, 1000);
	}

	// 2:5000毫秒後,執行任務,以後每隔1000毫秒再執行一次任務(無限執行)
	public static void test2() {
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.out.println("bombing!");
			}
		}, 5000, 1000);
	}

	
	//3:交替再生:任務2秒4秒交替的執行(無限執行),
	static int count = 0;
	public static void test3() {

		class MyTimerTask extends TimerTask {
			@Override
			public void run() {
				count = (count + 1) % 2;
				System.out.println("bombing!");
				new Timer().schedule(new MyTimerTask(), 2000 + count * 2000);
			}
		}
		new Timer().schedule(new MyTimerTask(), 2000);
	}

}

 

           4代碼

 

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

/**
 * @author Administrator @zsw 2012-7-20 下午08:08:42
 */
public class TraditionalTime2 {
	
    /*
     * 創建兩個循環交替任務:2秒後,A任務執行。
     * A任務裏面創建一個B任務4秒後執行,B任務裏面又創建一個A任務2秒後執行,,如此往復。
     * 
     */
	public static void main(String[] args) {
		TraditionalTime2 t2=new TraditionalTime2();
		new Timer().schedule(t2.new A(), 2000);
		
		 //用於打印時間秒數
		while (true) {
			System.out.println(new Date().getSeconds());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	class A extends TimerTask {
		@Override
		public void run() {
			System.out.println("A bombing!");
			new Timer().schedule(new B(), 4000);

		}

	}

	class B extends TimerTask {
		@Override
		public void run() {
			System.out.println("B bombing!");
			new Timer().schedule(new A(), 2000);

		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章