zoukankan      html  css  js  c++  java
  • Java中基于线程池的任务调度设计

          java中基于线程池的任务调度设计由广州疯狂软件教育java培训分享:

      基于Timer类的设计缺陷,java5中引入的ScheduledExecutor线程池设计。其设计思想是,每一个被调度的任务都会由线程池中一个线程去执行,因此任务是并发执行的,相互之间不会受到干扰。需要注意的是,只有当任务的执行时间到来时,ScheduedExecutor 才会真正启动一个线程,其余时间 ScheduledExecutor 都是在轮询任务的状态。

      实例代码:

      import java.util.concurrent.Executors;

      import java.util.concurrent.ScheduledExecutorService;

      import java.util.concurrent.TimeUnit;

      public class ScheduledExecutorTest implements Runnable {

      private String jobName = "";

      public ScheduledExecutorTest(String jobName) {

      this.jobName = jobName;

      }

      /*

      * (non-Javadoc)

      *

      * @see java.lang.Runnable#run()

      */

      public void run() {

      System.out.println("execute " + jobName);

      }

      public static void main(String[] args) {

      ScheduledExecutorService scheduledExecutorService = Executors

      .newScheduledThreadPool(10);

      long initialDelay1 = 1;

      long period1 = 1;

      // 从现在开始1秒钟之后,每隔1秒钟执行一次job1

      scheduledExecutorService.scheduleAtFixedRate(new ScheduledExecutorTest(

      "job1"), initialDelay1, period1,TimeUnit.SECONDS);

      long initialDelay2 = 1;

      long delay2 = 1;

      // 从现在开始2秒钟之后,每隔2秒钟执行一次job2

      scheduledExecutorService.scheduleWithFixedDelay(

      new ScheduledExecutorTest("job2"), initialDelay2, delay2,

      TimeUnit.SECONDS);

      }

      }

      运行结果:

      execute job1

      execute job2

      execute job1

      execute job2

      ScheduledExecutorService 中两种最常用的调度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。

      ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;

      ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay。

      由此可见,ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。

      TimeUnit:表示给定单元粒度的时间段,它提供在这些单元中进行跨单元转换和执行计时及延迟操作的实用工具方法。TimeUnit不维护时间信息,但是有助于组织和使用可能跨各种上下文单独维护的时间表示形式。毫微秒定义为千分之一微秒,微秒为千分之一毫秒,毫秒为千分之一秒,一分钟为六十秒,一小时为六十分钟,一天为二十四小时。

      疯狂软件教育中心紧扣IT前沿技术的脉搏,高瞻远瞩立于潮头,引领行业标杆,开创IT教育培训的新天地,被称为新式IT教育的“黄埔军校”。疯狂软件教育中心主要面向大学生和准大学生的长期就业培训、企业员工定制内训、在职工程师的短期高端培训以及企业级应用的产品研发,其专业服务和质量承诺在客户中赢得广泛的声誉。

      疯狂软件教育中心结合自身特色,打破固有思维模式,以突出实战性,系统性,学识转换相结合的理念体系指引下,注重如何将培训内容真正转化为实操经验,以此促进工作能力的达成。在疯狂软件学院,学员通过参与企业实际项目开发,学以致用,获得实际项目经验。凭借自身强悍的师资、一流的课程、真实的项目、超高的就业率已经让广大南方学子成功走上软件工程师职业道路,大量毕业即失业的学子已通过疯狂软件教育中心实现了就业。

  • 相关阅读:
    S3C44b0x通用延时函数,延时time个100us函数理解
    LeetCode-058-最后一个单词的长度
    LeetCode-053-最大子序和
    LeetCode-035-搜索插入位置
    LeetCode-027-移除元素
    LeetCode-026-删除有序数组中的重复项
    LeetCode-025-K 个一组翻转链表
    LeetCode-024-两两交换链表中的节点
    LeetCode-023-合并K个升序链表
    LeetCode-021-合并两个有序链表
  • 原文地址:https://www.cnblogs.com/gojava/p/3660248.html
Copyright © 2011-2022 走看看