scheduleAtFixedRate 与 scheduleWithFixedDelay 的区别

scheduleAtFixedRate 与 scheduleWithFixedDelay 的区别

 
 
package thread ;
import java.util.concurrent.Executors ;
import java.util.concurrent.ScheduledExecutorService ;
import java.util.concurrent.ScheduledFuture ;
import java.util.concurrent.ThreadFactory ;
import java.util.concurrent.ThreadPoolExecutor ;
import java.util.concurrent.TimeUnit ;
import java.util.concurrent.atomic.AtomicLong ;
public class Test03 {
private static final AtomicLong l = new AtomicLong ( 0 ) ;
private static final ScheduledExecutorService scheduler =
Executors . newScheduledThreadPool ( 10 );
public static void main ( String [] args ) {
/*
* 使用scheduleAtFixedRate , 该方法第三个参数表示在上一个个任务开始执行之后延迟
* 多少秒之后再执行, 是从上一个任务开始时开始计算
* 但是还是会等上一个任务执行完之后,下一个任务才开始执行,最后的结果,就是感觉延迟失去
* 了作用
* */
ScheduledFuture <?> sf1 = scheduler . scheduleAtFixedRate ( new Runnable () {
public void run () {
long i = l . getAndAdd ( 1 ) ;
System . out . println ( "start " + i );
try {
TimeUnit . SECONDS . sleep ( 5 ) ;
} catch ( InterruptedException e ) {
e . printStackTrace ();
}
System . out . println ( "end " + i );
}
}, 0 , 2 , TimeUnit . SECONDS ) ;
/*
* scheduleWithFixedDelay, 该方法第三个参数表示在上一个个任务结束执行之后延迟
* 多少秒之后再执行, 是从上一个任务结束时开始计算
* */
ScheduledFuture <?> sf2 = scheduler . scheduleWithFixedDelay ( new Runnable () {
public void run () {
long i = l . getAndAdd ( 1 ) ;
System . out . println ( "start " + i );
try {
TimeUnit . SECONDS . sleep ( 3 ) ;
} catch ( InterruptedException e ) {
e . printStackTrace ();
}
System . out . println ( "end " + i );
}
}, 0 , 2 , TimeUnit . SECONDS ) ;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值