如题。
直接在TimerTask中使用cancel()方法将其暂停后,
似乎无法直接再让它重新启动起来(直接在Timer中schedule这个已经cancel的timertask会抛出IllegalStateException异常)。实际需求为:
1. TimerTask中的run方法可以控制该TimerTask进入暂停状态
2. TimerTask进入暂停状态后,可以在其他类中调用某方法重新激活该TimerTask,使其进入定期运行状态
直接在TimerTask中使用cancel()方法将其暂停后,
似乎无法直接再让它重新启动起来(直接在Timer中schedule这个已经cancel的timertask会抛出IllegalStateException异常)。实际需求为:
1. TimerTask中的run方法可以控制该TimerTask进入暂停状态
2. TimerTask进入暂停状态后,可以在其他类中调用某方法重新激活该TimerTask,使其进入定期运行状态
在使用多线程时,使用一个标志来决定是否运行....
2. 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;
}
}
task.condition = true;
System.out.println("notify...");
task.notifyAll();
}
为什么要将task加到同步块中?
这个synchronized的具体作用是什么?
我试着去掉同步,结果会抛出“java.lang.IllegalMonitorStateException”异常。