直接在TimerTask中使用cancel()方法將其暫停后, 似乎無法直接再讓它重新啟動起來(直接在Timer中schedule這個已經cancel的timertask會拋出IllegalStateException異常)。
實際需求為: 1. TimerTask中的run方法可以控制該TimerTask進入暫停狀態(tài) 2. TimerTask進入暫停狀態(tài)后,可以在其他類中調用某方法重新激活該TimerTask,使其進入定期運行狀態(tài)
#1樓 得分:9回復于:2009-02-25 10:06:38 樓主可以將Timer換成多線程的啊.... 在使用多線程時,使用一個標志來決定是否運行.... |
#3樓 得分:100回復于: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回復于:2009-02-25 14:38:15 請問MT502 (3#) 如下這段代碼中: - Java code
synchronized (task) {
task.condition = true;
System.out.println("notify...");
task.notifyAll();
}
為什么要將task加到同步塊中? 這個synchronized的具體作用是什么? 我試著去掉同步,結果會拋出“java.lang.IllegalMonitorStateException”異常。 |
#7樓 得分:40回復于:2009-02-25 14:41:41 這是因為要調用某個對象的notify,wait方法,必須擁有該對象的監(jiān)視鎖,而該監(jiān)視鎖可以通過synchronized該對象獲得。 |
#8樓 得分:0回復于:2009-02-25 16:30:04
|