Java线程池中submit()和execute()方法有什么区别

两个方法都可以向线程池提交任务,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();
}
上一篇:多线程基础


下一篇:java中Executor、ExecutorService、ThreadPoolExecutor区别