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萬人。不論你是零基礎還是想提升,都可以找到適合的班型,千鋒教育隨時歡迎你來試聽。