美文网首页
2019-12-12java高级---->Thread之Sche

2019-12-12java高级---->Thread之Sche

作者: gdlooker | 来源:发表于2019-12-12 10:44 被阅读0次

    参考博客地址:https://www.cnblogs.com/huhx/p/baseusejavaScheduledExecutorService.html

    package cn.gdchent.springbootcommunity;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.*;
    
    /**
     * @auther:gdchent
     * @create:2019-12-12 10:07
     * @Description:
     */
    public class Test {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
    
            //定时线程池  执行定时任务方式1
            ScheduledExecutorService executorService= Executors.newSingleThreadScheduledExecutor();
            executorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    System.out.println("exe");
                }
            },10000,1000, TimeUnit.MILLISECONDS);
            System.out.println("=====ScheduledExecutorService使用Callable延迟运行====");
            ScheduledExecutorService executorService2= Executors.newSingleThreadScheduledExecutor();//单个定时类型的线程池
            //定时线程池  执行定时任务方式2
            List<Callable> callableList=new ArrayList<>();
            callableList.add(new MyCallableA());
            callableList.add(new MyCallableB());
            ScheduledFuture scheduleA =executorService2.schedule(callableList.get(0),4L,TimeUnit.SECONDS);
            ScheduledFuture scheduleB=executorService2.schedule(callableList.get(1),4L,TimeUnit.SECONDS);
            System.out.println(scheduleA.get());
            System.out.println(scheduleB.get());
        }
    
        static class MyCallableA implements Callable<String>{
            @Override
            public String call() throws Exception {
                System.out.println("a 当前线程开始执行:"+Thread.currentThread().getName()+","+System.currentTimeMillis());
                //休眠3s
                TimeUnit.SECONDS.sleep(3);
                System.out.println("a end up"+Thread.currentThread().getName()+","+System.currentTimeMillis());
                return "returnA";
            }
        }
    
        static class MyCallableB implements Callable<String> {
    
    
            @Override
            public String call() throws Exception {
                System.out.println("b 当前线程开始执行:"+Thread.currentThread().getName()+","+System.currentTimeMillis());
                //休眠3s
                TimeUnit.SECONDS.sleep(3);
                System.out.println("b end up"+Thread.currentThread().getName()+","+System.currentTimeMillis());
                return "returnb";
            }
        }
    }
    
    
    ScheduledExecutorService效果图.png

    相关文章

      网友评论

          本文标题:2019-12-12java高级---->Thread之Sche

          本文链接:https://www.haomeiwen.com/subject/tkizgctx.html