ThreadPoolExecutor线程池submit() 和 excute()区别,顺便带上Runnable和Callable

1、 实现Runnable接口和Callable接口的区别

如果想让线程池执行任务的话需要实现的Runnable接口或Callable接口。 Runnable接口或Callable接口实现类都可 以被ThreadPoolExecutor或ScheduledThreadPoolExecutor执行。

两者的区别一:

在于 Runnable 接口不会返回结果但 是 Callable 接口可以返回结果。

两者的区别二:

Callable接口的call()方法允许抛出异常;而Runnable接口的run()方法的异常只能在内部消化,不能继续上抛;

备注: 工具类 Executors 可以实现 Runnable 对象和 Callable 对象之间的相互转换。 ( Executors.callable(Runnable task) 或 Executors.callable(Runnable task,Object resule) )。

这里看Runnable和Callable的源代码就知道为什么Runnable 接口不会返回结果但 是 Callable 接口可以返回结果。实现 Runnable 接口和Callable 接口的主要目的是为了让线程执行call()或者run()里面的代码,而call()是有返回值的,run()没有返回值。

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}





@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
线程池中的submit()和execute()方法都可以用来将任务提交到线程池中,但是它们有一些不同之处。 submit()方法是ExecutorService接口中定义的方法,它返回一个Future对象,可以用来获取任务的执行结果或者取消任务的执行。submit()方法可以接受RunnableCallable类型的参数。 execute()方法是ThreadPoolExecutor类中定义的方法,它没有返回值,也不能获取任务的执行结果或者取消任务的执行。execute()方法只能接受Runnable类型的参数。 在实际使用中,一般使用submit()方法来提交任务,因为它可以更好地控制任务的执行情况,比如可以通过Future对象来获取任务的执行结果,或者通过cancel()方法来取消任务的执行。而execute()方法更适合一些简单的任务,比如打印日志等。 下面是submit()方法的使用示例: ```java ExecutorService executorService = Executors.newFixedThreadPool(10); Future<String> future = executorService.submit(new Callable<String>() { @Override public String call() throws Exception { return "Hello, World!"; } }); String result = future.get(); System.out.println(result); executorService.shutdown(); ``` 下面是execute()方法的使用示例: ```java ThreadPoolExecutor executorService = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); executorService.execute(new Runnable() { @Override public void run() { System.out.println("Hello, World!"); } }); executorService.shutdown(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值