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
------解决方案--------------------------------------------------------