1,Timer
Timer的實質上就是一個多線程,從它的類中可以看出:
Java代碼
1. private TimerThread thread = new TimerThread(queue);
它適用於與時間相關的一些操作,多長時間後運行某個動作,間隔運行某個動作。如:時鐘程式我們要每一秒中就重新整理一下我們的指標,如,類比心臟的跳動,Timer都是不錯的選擇。
2,Timer的線程設定成後台線程
Java代碼
1. public class Time {
2. private final Timer timer = new Timer(true);
3.
4. public void start() {
5. timer.schedule(new TimerTask() {
6. public void run() {
7. System.out.println("Your egg is ready!");
8. }
9. }, 1000, 1000);
10. }
11.
12. public static void main(String[] args) {
13. Time eggTimer = new Time();
14. eggTimer.start();
15. try {
16. Thread.sleep(5000);
17. } catch (InterruptedException e) {
18. e.printStackTrace();
19. }
20. }
21. }
public class Time {
private final Timer timer = new Timer(true);
public void start() {
timer.schedule(new TimerTask() {
public void run() {
System.out.println("Your egg is ready!");
}
}, 1000, 1000);
}
public static void main(String[] args) {
Time eggTimer = new Time();
eggTimer.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
實現了在1秒鐘後,每隔一秒鐘後運行一次TimerTask。這個Timer設定成的後台線程,在主線程退出後自動結束,一般的我覺得Timer 都設定成背景比較好,前段時間我就發現我寫的程式退出了,怎麼還有javaw.exe在工作管理員中沒有退出啊,還發現我的程式運行了很多次後,在工作管理員中的javaw.exe越來越多,我的機器也就越來越慢了,噢,肯定我的程式,還沒有完全推出,結果就找到了一個Timer沒有退出,後來我就把我程式的所有的Timer都改後台了。Timer一般都是完成某個任務,如果沒有了前台線程,它本來就沒有存在的意義了,我程式中是利用的Timer去檢測檔案的改動,然後通知前景程式檔案變了。
3,Timer運行一段時間,被cancel
Java代碼
1. public class Time {
2. private final static Timer timer = new Timer();
3.
4. public void start() {
5. timer.schedule(new TimerTask() {
6. public void run() {
7. System.out.println("Your egg is ready!");
8. }
9. }, 1000, 1000);
10. }
11.
12. public static void main(String[] args) {
13. Time eggTimer = new Time();
14. eggTimer.start();
15. try {
16. Thread.sleep(5000);
17. timer.cancel();
18. } catch (InterruptedException e) {
19. e.printStackTrace();
20. }
21. }
22. }
public class Time {
private final static Timer timer = new Timer();
public void start() {
timer.schedule(new TimerTask() {
public void run() {
System.out.println("Your egg is ready!");
}
}, 1000, 1000);
}
public static void main(String[] args) {
Time eggTimer = new Time();
eggTimer.start();
try {
Thread.sleep(5000);
timer.cancel();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
4,Timer運行5次後,被cancel
Java代碼
1. public class Time {
2. private final static Timer timer = new Timer();
3.
4. public void start() {
5. timer.schedule(new TimerTask() {
6. private int count = 5;
7. public void run() {
8. System.out.println("Your egg is ready!");
9. if(count--==0)
10. timer.cancel();
11. }
12. }, 1000, 1000);
13. }
14.
15. public static void main(String[] args) {
16. Time eggTimer = new Time();
17. eggTimer.start();
18. }
19. }
轉自:http://xmind.javaeye.com/blog/718699