直接在TimerTask中使用cancel()方法將其暫停后,
似乎無法直接再讓它重新啟動(dòng)起來(直接在Timer中schedule這個(gè)已經(jīng)cancel的timertask會(huì)拋出IllegalStateException異常)。
實(shí)際需求為:
1. TimerTask中的run方法可以控制該TimerTask進(jìn)入暫停狀態(tài)
2. TimerTask進(jìn)入暫停狀態(tài)后,可以在其他類中調(diào)用某方法重新激活該TimerTask,使其進(jìn)入定期運(yùn)行狀態(tài)
#1樓 得分:9回復(fù)于:2009-02-25 10:06:38
樓主可以將Timer換成多線程的啊....
在使用多線程時(shí),使用一個(gè)標(biāo)志來決定是否運(yùn)行....
#3樓 得分:100回復(fù)于:2009-02-25 10:33:21
Java code
import java.util.Timer;import java.util.TimerTask;public class Test1 { public static void main(String[] args) { final MyTimerTask task = new MyTimerTask(); new Timer().scheduleAtFixedRate(task, 0, 1000); Thread thread = new Thread() { public void run() { while(true) { try { Thread.sleep(1500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (task) { task.condition = true; System.out.println("notify..."); task.notifyAll(); } } }; }; thread.start(); }}class MyTimerTask extends TimerTask{ public volatile boolean condition = false; public void run() { synchronized (this) { while(!condition) { System.out.println("Waiting..."); try { wait(); } catch (InterruptedException e) { Thread.interrupted(); } } } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Continue task...Done."); condition = false; }}
#6樓 得分:0回復(fù)于:2009-02-25 14:38:15
請問MT502 (3#)
如下這段代碼中:
Java code
synchronized (task) { task.condition = true; System.out.println("notify..."); task.notifyAll(); }
為什么要將task加到同步塊中?
這個(gè)synchronized的具體作用是什么?
我試著去掉同步,結(jié)果會(huì)拋出“java.lang.IllegalMonitorStateException”異常。
#7樓 得分:40回復(fù)于:2009-02-25 14:41:41
引用 6 樓 talent_marquis 的回復(fù):
請問MT502
如下這段代碼中:
Java code
synchronized (task) {
task.condition = true;
System.out.println("notify...");
task.notifyAll();
}
為什么要將task加到同步塊中?
這個(gè)synchronized的具體作用是什么?
我試著去掉同步,結(jié)果會(huì)拋出“java.lang.IllegalMonitorStateException”異常。
這是因?yàn)橐{(diào)用某個(gè)對象的notify,wait方法,必須擁有該對象的監(jiān)視鎖,而該監(jiān)視鎖可以通過synchronized該對象獲得。
#8樓 得分:0回復(fù)于:2009-02-25 16:30:04
非常感謝!