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>