ScheduledThreadPoolExecutor类里方法例子总结

ScheduledThreadPoolExecutor类方法理解总结:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestScheduledThreadPoolExecutor {
private static SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");

public static void main(String[] args) {
// ScheduledExecutorService exec=Executors.newScheduledThreadPool(1);
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
/**
* 每隔一段时间打印系统时间,互不影响的<br/> 创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;<br/>
* 也就是将在 initialDelay 后开始执行,然后在initialDelay+period 后执行,<br/> 接着在
* initialDelay + 2 * period 后执行,依此类推。
*/
exec.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println(format.format(new Date()));
}
}, 1000, 5000, TimeUnit.MILLISECONDS);

// 开始执行后就触发异常,next周期将不会运行
exec.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out
.println("RuntimeException no catch,next time can't run");
throw new RuntimeException();
}
}, 1000, 5000, TimeUnit.MILLISECONDS);

// 虽然抛出了运行异常,当被拦截了,next周期继续运行
exec.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
throw new RuntimeException();
} catch (Exception e) {
System.out.println("RuntimeException catched,can run next");
}
}
}, 1000, 5000, TimeUnit.MILLISECONDS);

/**
* 创建并执行一个在给定初始延迟后首次启用的定期操作,<br/> 随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。
*/
exec.scheduleWithFixedDelay(new Runnable() {
public void run() {
System.out.println("scheduleWithFixedDelay:begin,"
+ format.format(new Date()));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("scheduleWithFixedDelay:end,"
+ format.format(new Date()));
}
}, 1000, 5000, TimeUnit.MILLISECONDS);

/**
* 创建并执行在给定延迟后启用的一次性操作。
*/
exec.schedule(new Runnable() {
public void run() {
System.out.println("The thread can only run once!");
}
}, 5000, TimeUnit.MILLISECONDS);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值