Timer中的
   schedule(TimerTask task, long delay, long period) 方法是:
       安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。
   cancel() 方法是:
       丢弃所有当前已安排的任务。但不会干扰当前正在执行的任务(如果存在)。如果我在调用cancel()时,Timer正在执行任务,那有没有类似jion()的方法,来等待最后执行的那个任务结束的方法呢?   //停止循环执行任务
   timer.cancel();
   timer.join();//我想等待timer最后执行的任务结束,但找不到合适的方法,怎么办?
   //关闭数据库连接池
   DBConnectionPool.shutdown();

解决方案 »

  1.   

    使用java.util.concurrent.ExecutorService
      

  2.   

    ExecutorServiceshutdown():
    Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.boolean awaitTermination(long timeout, TimeUnit unit) 
    Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.boolean isShutdown() 
    Returns true if this executor has been shut down.boolean isTerminated() 
    Returns true if all tasks have completed following shut down.
      

  3.   

    ExecutorService es = Executors.newFixedThreadPool(4);
    executor.invokeAll(tasks);或者用 CountDownLatch 来做
      

  4.   

    抱歉!~,我的问题没描述清楚。假如我用计时器timer每30秒一次循环执行某任务
    在调用timer.cancel()方法后,会清除计时器timer上安排的任务。但是在调用cancel()方法时,程序会有以下2种状态
      1.计时器整好处于空闲状态,并没有执行这个任务。
        那么在后续处理中,我就可以直接关闭数据库连接池了(任务里会使用数据库连接池里的Connection来操作数据)
      2.计时器正在执行任务,此时调用cancel()方法不会影响这个正在执行的任务。
        那么数据库连接池里的DB连接可能正在使用中,我就不能立刻关闭数据库连接池,而是要等待这个任务结束后,再关闭数据库连接池。
        但是我该如何等待呢?我想了一下,最简单的办法是使用一个标志位runFlag来控制。
            在任务开始执行时:runFlag ← true
            在任务结束执行时:runFlag ← false
        然后再调用cancel()后,去判断这个标志位:
            timer.cancel();
            while(runFlag){
                sleep(100);
            }

            DBConnectionPool.shutdown();    但是使用轮询判断的方法,总是在白白的耗费cpu资源,有没有更正规的办法呢?---------------------
     * 至于用这个类ExecutorService来循环执行一个任务,我还不清楚怎么做,去研究下。
      

  5.   

    一些关键字可以解决你的问题:Executors#newScheduledThreadPool(int corePoolSize) 
    ScheduledExecutorService#shutdown
    ScheduledExecutorService#awaitTermination
      

  6.   

    是的,你需要的其实就是一个任务方的主动通知,以回调的方式。也就可以避免轮询了。ticmy说的awaitTermination就是回调方法。
    boolean awaitTermination(long timeout,
                             TimeUnit unit)
                             throws InterruptedException    Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first. 
    这里有个例子:
    http://stackoverflow.com/questions/6767906/how-to-run-outstanding-tasks-immediately-after-executorservice-shutdown