日期:2014-05-20  浏览次数:20725 次

计时器Timer有没有等待任务结束的方法
Timer中的
  schedule(TimerTask task, long delay, long period) 方法是:
  安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。
  cancel() 方法是:
  丢弃所有当前已安排的任务。但不会干扰当前正在执行的任务(如果存在)。

如果我在调用cancel()时,Timer正在执行任务,那有没有类似jion()的方法,来等待最后执行的那个任务结束的方法呢?

  //停止循环执行任务
  timer.cancel();
  timer.join();//我想等待timer最后执行的任务结束,但找不到合适的方法,怎么办?
  //关闭数据库连接池
  DBConnectionPool.shutdown();

------解决方案--------------------
ExecutorService

shutdown():
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.
------解决方案--------------------
ExecutorService es = Executors.newFixedThreadPool(4);
executor.invokeAll(tasks);

或者用 CountDownLatch 来做
------解决方案--------------------
一些关键字可以解决你的问题:

Executors#newScheduledThreadPool(int corePoolSize) 
ScheduledExecutorService#shutdown
ScheduledExecutorService#awaitTermination


探讨

抱歉!~,我的问题没描述清楚。

假如我用计时器timer每30秒一次循环执行某任务
在调用timer.cancel()方法后,会清除计时器timer上安排的任务。

但是在调用cancel()方法时,程序会有以下2种状态
1.计时器整好处于空闲状态,并没有执行这个任务。
那么在后续处理中,我就可以直接关闭数据库连接池了(任务里会使用数据库连接池里的Connection……

------解决方案--------------------
探讨

抱歉!~,我的问题没描述清楚。

假如我用计时器timer每30秒一次循环执行某任务
在调用timer.cancel()方法后,会清除计时器timer上安排的任务。

但是在调用cancel()方法时,程序会有以下2种状态
1.计时器整好处于空闲状态,并没有执行这个任务。
那么在后续处理中,我就可以直接关闭数据库连接池了(任务里会使用数据库连接池里的Connection……