Java runnable和callable的异同
1、相同点
两者都是接口
两者都需要调用Thread.start启动线程
2、不同点
callable的核心是call()方法,允许返回值,runnable的核心是run()方法,没有返回值
call()方法可以抛出异常,但是run()方法不行
callable和runnable都可以应用于executors,thread类只支持runnable
3、实例
Runnable和Callable的接口定义
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface Runnable
is used
* to create a thread, starting the thread causes the object's
* run
method to be called in that separately executing
* thread.
*
* The general contract of the method run
is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
@FunctionalInterface
public interface Callable{
/**
* 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;
}
以上就是Java runnable和callable的异同,希望对大家有所帮助。更多关于“java培训”的问题,欢迎咨询千锋教育在线名师。千锋教育多年办学,课程大纲紧跟企业需求,更科学更严谨,每年培养泛IT人才近2万人。不论你是零基础还是想提升,都可以找到适合的班型,千锋教育随时欢迎你来试听。