公众号:架构师与哈苏
关注公众号进入it交流群! 公众号:架构师与哈苏 不定时都会推送一些实用的干货。。。

两个方法都可以向线程池提交任务,execute()方法的返回类型是void,它定义在Executor接口中,而submit()方法返回有计算结构的Future对象,它定义在ExecutorService接口中,它拓展了Executor接口,其他线程池类像ThreadPoolExecutor和ScheduledThreadPoolExecutor都有这些方法。

submit()

public static void submit() throws ExecutionException, InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    Callable callable = () -> {
        Thread.sleep(4000);
        return "我是结果!";
    };
    Future future = executorService.submit(callable);
    //关闭连接池
    executorService.shutdown();
    //同步获取结果
    String str = future.get().toString();
    System.out.println("str:" + str);
}

execute()

public static void execute(){
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    Runnable runnable = () -> {
        System.out.println("hello runnable!");
    };
    executorService.execute(runnable);
    //关闭连接池
    executorService.shutdown();
}
posted on 2021-08-05 16:21  公众号/架构师与哈苏  阅读(249)  评论(0编辑  收藏  举报