如题。
直接在TimerTask中使用cancel()方法将其暂停后,
似乎无法直接再让它重新启动起来(直接在Timer中schedule这个已经cancel的timertask会抛出IllegalStateException异常)。实际需求为:
1. TimerTask中的run方法可以控制该TimerTask进入暂停状态
2. TimerTask进入暂停状态后,可以在其他类中调用某方法重新激活该TimerTask,使其进入定期运行状态

解决方案 »

  1.   

    楼主可以将Timer换成多线程的啊....
    在使用多线程时,使用一个标志来决定是否运行....
      

  2.   

    1. 项目需求要求用Timer+TimerTask实现
    2. Timer本身就是另外启动一个线程
      

  3.   

    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;
    }
    }
      

  4.   

    请问MT502 如下这段代码中:synchronized (task) {
                            task.condition = true;
                            System.out.println("notify...");
                            task.notifyAll();
                        }
    为什么要将task加到同步块中?
    这个synchronized的具体作用是什么?
    我试着去掉同步,结果会抛出“java.lang.IllegalMonitorStateException”异常。
      

  5.   

    这是因为要调用某个对象的notify,wait方法,必须拥有该对象的监视锁,而该监视锁可以通过synchronized该对象获得。