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

2019-12-12  本文已影响0人  gdlooker

参考博客地址: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
上一篇下一篇

猜你喜欢

热点阅读