Timer和ScheduledThreadPoolExecutor小例子

来源:互联网 发布:淘宝卖家店铺名怎么改 编辑:程序博客网 时间:2024/04/27 05:00
<pre name="code" class="java">                //1、固定速率执行//A - 如果执行时间 > 周期执行间隔事件,则马上执行//B - 如果执行时间 < 周期执行间隔时间,则延迟到到达间隔事件执行Timer timer = new Timer();timer.scheduleAtFixedRate(new TimerTask() {int count;SimpleDateFormat sf = new SimpleDateFormat("hh:mm:ss:SSS");@Overridepublic void run() {String nowTime;count++;try {nowTime = sf.format(new Date(System.currentTimeMillis()));System.out.println(count + "/" + nowTime);Thread.currentThread().sleep(500);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}, 500, 1000);//2、非速率执行//A - 如果执行时间 > 周期执行间隔事件,则马上执行//B - 如果执行时间 < 周期执行间隔时间,则延迟到到达间隔事件执行Timer timerTwo = new Timer();timerTwo.schedule(new TimerTask() {int count;SimpleDateFormat sf = new SimpleDateFormat("hh:mm:ss:SSS");@Overridepublic void run() {String nowTime;count++;try {nowTime = sf.format(new Date(System.currentTimeMillis()));System.out.println(count + "/" + nowTime);Thread.currentThread().sleep(500);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}, 0, 1000);//1、scheduleAtFixedRate周期执行//A - 如果执行时间 > 周期执行间隔事件,则马上执行//B - 如果执行时间 < 周期执行间隔时间,则延迟到到达间隔事件执行ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(3);pool.scheduleAtFixedRate(new Runnable() {int count;SimpleDateFormat sf = new SimpleDateFormat("hh:mm:ss:SSS");@Overridepublic void run() {String nowTime;count++;try {nowTime = sf.format(new Date(System.currentTimeMillis()));System.out.println(count + "/" + nowTime);Thread.currentThread().sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}, 0, 1000, TimeUnit.MILLISECONDS);//1、scheduleWithFixedDelay周期执行//A - 如果执行时间 > 周期执行间隔事件,任务结束后还需要等待到间隔事件之后才执行//B - 如果执行时间 < 周期执行间隔时间,任务结束后还需要等待到间隔事件之后才执行ScheduledThreadPoolExecutor poolTwo = new ScheduledThreadPoolExecutor(3);poolTwo.scheduleWithFixedDelay(new Runnable() {int count;SimpleDateFormat sf = new SimpleDateFormat("hh:mm:ss:SSS");@Overridepublic void run() {String nowTime;count++;try {nowTime = sf.format(new Date(System.currentTimeMillis()));System.out.println(count + "/" + nowTime);Thread.currentThread().sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}, 0, 2000, TimeUnit.MILLISECONDS);


                                             
0 0