Java并发之ScheduledExecutorService(schedule、scheduleAtFixedRate、scheduleWithFixedDelay)

 1 package com.thread.test.thread;
 2 import java.util.Timer;
 3 import java.util.TimerTask;
 4 import java.util.concurrent.*;
 5 import java.util.concurrent.locks.ReentrantLock;
 6 
 7 /**
 8  * schedule(Runnable command, long delay, TimeUnit unit)
 9  * @ command: 需要执行的任务
10  * @ delay:任务执行需要延迟的时间
11  * @ unit:时间单位
12  *
13  * 一次性执行任务,执行完成结束
14  *
15  * ScheduledExecutorService:
16  * scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
17  * @ Runnable command: 需要执行的任务
18  * @ long initialDelay:第一次执行延迟的时间
19  * @ long period:间隔周期
20  * @ TimeUnit unit
21  *
22  * 包含首次延迟的周期性执行任务,第一次执行:delay+period,第二次:delay+2*period,以此类推...
23  * 停止:异常停止执行,主动调用停止方法
24  * 如果某一个周期执行时间超过设定的period,则后续顺延
25  *
26  * scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
27  * @ command: 需要执行的任务
28  * @ initialDelay:第一次执行延迟的时间
29  * @ delay:周期之间的延迟,间隔
30  * @ unit:前两个参数的单位
31  *
32  * 周期性执行任务:第一次执行:initialDelay+delay,第二次:initialDelay+2*delay,以此类推...
33  * 停止:异常停止执行,主动调用停止方法
34  * 不顺延
35  *
36  * Created by windwant on 2016/5/26.
37  */
38 public class MyExecutor {
39     public static void main(String[] args) {
40         testTimer();
41     }
42 
43     public static void testTimer(){
44         new Timer().schedule(new MyTimerTask(), 2000, 5000);
45     }
46 
47     public static void testExecutors(){
48         MyERunnable mer = new MyERunnable(5);
49 //        ExecutorService es = Executors.newCachedThreadPool();
50 //        ExecutorService es = Executors.newFixedThreadPool(2);
51         ScheduledExecutorService es = Executors.newScheduledThreadPool(2);
52         es.schedule(mer, 10000, TimeUnit.SECONDS.MILLISECONDS);
53         es.scheduleAtFixedRate(mer, 2, 10, TimeUnit.SECONDS);
54         es.scheduleWithFixedDelay(mer, 1, 5, TimeUnit.SECONDS);
55         es.shutdown();
56     }
57 }
58 
59 class MyERunnable implements Runnable{
60     private int num = 0;
61     MyERunnable(int num){
62         this.num = num;
63     }
64     public void run() {
65         ReentrantLock lock = new ReentrantLock();
66         try{
67             lock.lock();
68             for (int i = 0; i < num; i++) {
69                 System.out.println("current thread: " + Thread.currentThread().getName() + " num--" + i);
70                 Thread.sleep(1000);
71             }
72         }catch (Exception e){
73             e.printStackTrace();
74         }finally {
75             lock.unlock();
76         }
77     }
78 }
79 
80 class MyTimerTask extends TimerTask{
81 
82     @Override
83     public void run() {
84         System.out.println("timer task");
85     }
86 }

项目地址:https://github.com/windwant/windwant-demo/tree/master/thread-demo

    原文作者:WindWant
    原文地址: https://www.cnblogs.com/niejunlei/p/5985291.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞