java设置任务异步执行

public class DemoApplication {
    private static ExecutorService pool;

    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
        SpringApplication.run(DemoApplication.class, args);
        System.out.println("test 开始");
        test1();
        System.out.println("test 结束");
    }

    private static void test1() {
        pool = new  ThreadPoolExecutor(5,20,1000,TimeUnit.MILLISECONDS,
                new SynchronousQueue<Runnable>(),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        pool.submit(() -> new DemoApplication().longTimeMethod());
    }
    
    public void longTimeMethod() {
        try {
            System.out.println("============开始============");
            Thread.sleep(2000);
            System.out.println("============结束============");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

 

posted @ 2021-06-01 22:04  MartialWorldFish  阅读(208)  评论(0编辑  收藏  举报