zoukankan      html  css  js  c++  java
  • ScheduledExecutorService

    项目中用到了ScheduledExecutorService这里简单写了个demo留以后复习

    job工作

    package org.ScheduledExecutorService;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class RunnableJob implements Runnable{
    
        private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        
        @Override
        public void run() {
    
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("The current time is " + sdf.format(new Date()) + ".");
        }
    
    }

    测试类

    package org.ScheduledExecutorService;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.Callable;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    
    public class ScheduledExecutorServiceTest {
    
        private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        
        private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
    
        /**
         * 初始化延迟1s开始执行,每隔3s重新执行一次任务。
         */
        public void scheduleAtFixedRateTest() {
            executor.scheduleAtFixedRate(new RunnableJob(), 1, 3, TimeUnit.SECONDS);
        }
        
        /**
         * 初始化时延时1s开始执行,本次执行结束后延迟4s开始下次执行。
         */
        public void scheduleWithFixedDelayTest(){
            executor.scheduleWithFixedDelay(new RunnableJob(), 1, 4, TimeUnit.SECONDS);
        }
        
        public void scheduleRunnableTest(){
            executor.schedule(new RunnableJob(), 3, TimeUnit.SECONDS);
        }
        
        public void scheduleTest(){
    /*        executor.schedule(new Callable<V>() {
            }, delay, unit)*/
        }
        public static void main(String[] args) {
            ScheduledExecutorServiceTest sest = new ScheduledExecutorServiceTest();
            System.out.println("start time is " + sdf.format(new Date()));
        //    sest.scheduleAtFixedRateTest();
        //    sest.scheduleWithFixedDelayTest();
            sest.scheduleRunnableTest();
        }
    }
  • 相关阅读:
    react 创建组件 (三)PureComponet
    [翻译] YLGIFImage 高效读取GIF图片
    iOS设计模式:静态工厂相关
    使用mac版思维导图软件MindNode
    使用NSHashTable存储引用对象
    [翻译] PBJNetworkObserver 网络监控
    使用富文本OHAttributedLabel
    [翻译] TLMotionEffect 重力感应
    [翻译] TSActivityIndicatorView 自定义指示器
    获取音视频文件AVMetadata数据
  • 原文地址:https://www.cnblogs.com/vincentren/p/5648504.html
Copyright © 2011-2022 走看看