[在线等]如何暂停/重启(Pause/Restart)一个TimerTask而不是销毁/新建(Cancel/Renew)一个TimerTask

talent_marquis 2009-02-25 10:00:27
如题。
直接在TimerTask中使用cancel()方法将其暂停后,
似乎无法直接再让它重新启动起来(直接在Timer中schedule这个已经cancel的timertask会抛出IllegalStateException异常)。

实际需求为:
1. TimerTask中的run方法可以控制该TimerTask进入暂停状态
2. TimerTask进入暂停状态后,可以在其他类中调用某方法重新激活该TimerTask,使其进入定期运行状态
...全文
1867 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
fei80230901 2009-02-25
  • 打赏
  • 举报
回复
学习
talent_marquis 2009-02-25
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 MT502 的回复:]
Java codeimport 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 {

[/Quote]

谢谢,我在真实环境中测试一下这种思路。
MT502 2009-02-25
  • 打赏
  • 举报
回复
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;
}
}
talent_marquis 2009-02-25
  • 打赏
  • 举报
回复
1. 项目需求要求用Timer+TimerTask实现
2. Timer本身就是另外启动一个线程
paullbm 2009-02-25
  • 打赏
  • 举报
回复
楼主可以将Timer换成多线程的啊....
在使用多线程时,使用一个标志来决定是否运行....
talent_marquis 2009-02-25
  • 打赏
  • 举报
回复
非常感谢!
MT502 2009-02-25
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 talent_marquis 的回复:]
请问MT502

如下这段代码中:

Java code
synchronized (task) {
task.condition = true;
System.out.println("notify...");
task.notifyAll();
}




为什么要将task加到同步块中?
这个synchronized的具体作用是什么?
我试着去掉同步,结果会抛出“java.lang.IllegalMonitorStateException”异常。
[/Quote]
这是因为要调用某个对象的notify,wait方法,必须拥有该对象的监视锁,而该监视锁可以通过synchronized该对象获得。
talent_marquis 2009-02-25
  • 打赏
  • 举报
回复
请问MT502

如下这段代码中:

synchronized (task) {
task.condition = true;
System.out.println("notify...");
task.notifyAll();
}


为什么要将task加到同步块中?
这个synchronized的具体作用是什么?
我试着去掉同步,结果会抛出“java.lang.IllegalMonitorStateException”异常。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧