测试一
- public static void method_02() {
- ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
-
- executor.scheduleAtFixedRate(new Runnable() {
- @Override
- public void run() {
- long start = new Date().getTime();
- System.out.println("scheduleAtFixedRate 开始执行时间:" +
- DateFormat.getTimeInstance().format(new Date()));
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- long end = new Date().getTime();
- System.out.println("scheduleAtFixedRate 执行花费时间=" + (end - start) / 1000 + "m");
- System.out.println("scheduleAtFixedRate 执行完成时间:" + DateFormat.getTimeInstance().format(new Date()));
- System.out.println("======================================");
- }
- }, 1, 5, TimeUnit.SECONDS);
- }
执行结果
测试二
总结:以上两种方式不同的地方是任务的执行时间,如果间隔时间大于任务的执行时间,任务不受执行时间的影响。如果间隔时间小于任务的执行时间,那么任务执行结束之后,会立马执行,至此间隔时间就会被打乱。
测试一
- public static void method_03() {
- ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
-
- executor.scheduleWithFixedDelay(new Runnable() {
- @Override
- public void run() {
- long start = new Date().getTime();
- System.out.println("scheduleWithFixedDelay 开始执行时间:" +
- DateFormat.getTimeInstance().format(new Date()));
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- long end = new Date().getTime();
- System.out.println("scheduleWithFixedDelay执行花费时间=" + (end - start) / 1000 + "m");
- System.out.println("scheduleWithFixedDelay执行完成时间:"
- + DateFormat.getTimeInstance().format(new Date()));
- System.out.println("======================================");
- }
- }, 1, 2, TimeUnit.SECONDS);
- }
执行结果
(编辑:ASP站长网)
|