为了弥补Timer 的上述缺陷,在Java 5的时候推出了基于线程池设计的 ScheduledExecutor。其设计思想是:每一个被调度的任务都会由线程池中一个线程去执行,因此任务是并发执行的,相互之间不会受到干扰。但需要注意的是只有当任务的执行时间到来时,ScheduedExecutor 才会真正启动一个线程,其余时间 ScheduledExecutor 都是在轮询任务的状态。

public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textView = (TextView) findViewById(R.id.text);
testScheduledExecutorWay();
}
private static void testScheduledExecutorWay(){
ScheduledExecutorService service = Executors.newScheduledThreadPool(10);//创建线程池的方式有几种,可以根据业务具体选择 long initialDelay1 = 1;
long period1 = 1;
// 从现在开始1秒钟之后,每隔1秒钟执行一次job1
service.scheduleAtFixedRate(
new ScheduledExecutorTest("job1"), initialDelay1,
period1, TimeUnit.SECONDS); long initialDelay2 = 1;
long delay2 = 1;
// 从现在开始1秒钟之后,每隔1秒钟执行一次job2
service.scheduleWithFixedDelay(
new ScheduledExecutorTest("job2"), initialDelay2,
delay2, TimeUnit.SECONDS);
} static class ScheduledExecutorTest implements Runnable{
private String jobName = ""; public ScheduledExecutorTest(String jobName) {
super();
this.jobName = jobName;
} @Override
public void run() {
System.out.println(getNowTime()+"执行作业:" + jobName);
}
} public static String getNowTime(){
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");// 可以方便地修改日期格式
return dateFormat.format(now);
} }

ScheduledExecutorService 中两种最常用的调度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。其中ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;而ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay。所以两种方式异同在于ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。

最新文章

  1. Binary Tree Postorder Traversal
  2. javaWeb——图片验证
  3. Oracle 正则表达式函数-REGEXP_LIKE 使用例子
  4. sdut2169:Sequence(dp)
  5. SSIS使用OleDB和Ado.Net两种方式调用 存储过程
  6. Xdebug的安装与使用
  7. [Stephen]Export from Excel to ALM
  8. 一个ShellExecute的超全说明(www.phidels.com这个网站很多内容)
  9. 在CentOS/RHEL/Scientific Linux 6下安装 LAMP
  10. CSS3学习系列之背景相关样式(一)
  11. maven仓库--搭建局域网私服(windows版)
  12. 201521123108 《Java程序设计》第7周学习总结
  13. Bootstrap3基础 栅格系统 col-md-offset 向右偏移
  14. JDBC-Transaction
  15. 牛客网练习赛t2(线段树)
  16. Jmeter的Body Data里输入中文时乱码
  17. PetaPoco在ASP.NET Core 2.2中使用注入方式访问数据库
  18. 自学Linux Shell3.3-列表命令ls
  19. SYSAUX表空间如何清理
  20. 关于Vue中的 render: h => h(App) 具体是什么含义?

热门文章

  1. API测试-接口测试基础(1)
  2. Qt 展示pdf内容(新窗口或嵌入,pdfjs,linux)
  3. ASP.NET Web API 2系列(四):基于JWT的token身份认证方案
  4. Nginx【常见知识点速查】
  5. 趣图:普通人讲故事 VS 程序员讲故事
  6. 使用spring mvc拦截器 会话失效处理
  7. python类中的__init__和__new__方法
  8. linux_命令格式和命令提示符
  9. Python练习题 030:Project Euler 002:偶数斐波那契数之和
  10. CTFshow_Web入门源码