刚开始学线程池的定时任务,用到了scheduleAtFixedRate方法,
package test;
public class work implements Runnable {
@Override
public void run() {
int i=0;
while(i<10) {
System.out.println(i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package test;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class errpool {
public static void main(String[] args) {
ScheduledExecutorService pool = new ScheduledThreadPoolExecutor(10);
pool.scheduleAtFixedRate(new work(), 0, 5, TimeUnit.SECONDS);
}
}
我查的教程说:
当执行任务的时间大于周期间隔时,会发生什么呢?
(1)schedule方法:下一次执行时间相对于 上一次 实际执行完成的时间点 ,因此执行时间会不断延后
(2)scheduleAtFixedRate方法:下一次执行时间相对于上一次开始的 时间点 ,因此执行时间不会延后,存在并发性
按他说的我的定时设置的5秒,但是程序执行要10秒,应该符合第二条,但是实际的运行结果如下
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
并没有出现并发现象,这是为啥呢,求大神解答
看 API
/**
* Creates and executes a periodic action that becomes enabled first
* after the given initial delay, and subsequently with the given
* period; that is executions will commence after
* {@code initialDelay} then {@code initialDelay+period}, then
* {@code initialDelay + 2 * period}, and so on.
* If any execution of the task
* encounters an exception, subsequent executions are suppressed.
* Otherwise, the task will only terminate via cancellation or
* termination of the executor. If any execution of this task
* takes longer than its period, then subsequent executions
* may start late, but will not concurrently execute.
*
* @param command the task to execute
* @param initialDelay the time to delay first execution
* @param period the period between successive executions
* @param unit the time unit of the initialDelay and period parameters
* @return a ScheduledFuture representing pending completion of
* the task, and whose {@code get()} method will throw an
* exception upon cancellation
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if command is null
* @throws IllegalArgumentException if period less than or equal to zero
*/
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
重点在这里:
If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
如果执行时间比中间的周期长,随后的执行任务可能会晚一点,不会同时执行。
一切 按照API分析