java.util中的Timer和TimerTask,怎么保证task一定是顺序执行的?
比如这样写:timer.schedule(task, 0, 2000);
如果我的task执行需要5秒,timer会等前面的task执行完再执行下一个task;还是2秒后就立即启用新的线程执行后面的task?
如果是后者,想达到前面的效果如何写?

解决方案 »

  1.   

    jdk1.5测了下应该是前者,看下1.6.。。
      

  2.   

    timer是执行完在启动定时的。
      

  3.   

    API中说得很清楚:
    在固定延迟执行中,根据前一次执行的实际执行时间来安排每次执行。如果由于任何原因(如垃圾回收或其他后台活动)而延迟了某次执行,则后续执行也将被延迟。
      

  4.   

    呵呵,看看api就知道了
    有2个函数:
    public void scheduleAtFixedRate(TimerTask task,
                                    long delay,
                                    long period)public void schedule(TimerTask task,
                         Date firstTime,
                         long period);第一个可以满足你的需求
      

  5.   

    Timer 是使用后者的,如果每秒执行一次,每执行一次要耗时两秒,这样的话要执行的会越积越多,上一次与下一次运行的间隔不会是 1 秒钟。这是 Timer 设计上的缺陷,从 JDK 5 起一般没有必要再使用 Timer 了,可以使用 JDK 并发包中的 ScheduledExecutorService 进行定时任务。import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;public class Test {    public static void main(String[] args) {
            ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
            service.scheduleWithFixedDelay(new ScheduleRunnable(), 0, 1, TimeUnit.SECONDS);
        }
        
        private static class ScheduleRunnable implements Runnable {
            public void run() {
                System.out.printf("%tF %<tT%n", System.currentTimeMillis());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.printf(">> %tF %<tT%n", System.currentTimeMillis());
            }        
        }
    }
      

  6.   


    package csdnTread;import java.util.Timer;
    import java.util.TimerTask;import javax.swing.JOptionPane;public class TimerTaskTest 
    { public static void main(String args[])
    {
    TimerTask task=new TimerTask()
    {



    public  void run() 
    {

        System.out.println("task  is  runing---第一次");
        try 
        {
    Thread.sleep(3000);
    } catch (InterruptedException e) 
    {
    // TODO Auto-generated catch block
    JOptionPane.showMessageDialog(null,"被中断");
    }
     System.out.println("task  is  runing---第二次");
    }

    };
    Timer timer=new Timer();
    timer.schedule(task,2000,2000);
    }
    }
    用这个代码试了下!!、我发现!!当Timer执行完毕后,Task还没执行完!整个进程将全部延迟!!
    并不是在是按照timer.schedule(task,2000,2000);这里规定的时间价格!
    而是变为3秒!!
    但是你还会发现  打印出
    task  is  runing---第一次
    之后
    task  is  runing---第二次
    task  is  runing---第一次
    几乎是同时打印出!
    这说明!!这是这是Timer其实已经计时了!只是等待TimerTask执行完毕后!才执行
    如果觉得时间间隔1秒不足证明的 话可以把  Timer和TimerTask时间差变大写
    Thread.sleep(4000);