Java常见面试题—Callable与Runnable接口

Runnable

Runnable应该是比较熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值,不能将结果返回给客户程序。然后使用某个线程去执行runnable即可实现多线程,Thread类在调用start()函数后就是执行的是Runnable的run()函数。Runnable的声明如下 :

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> 
     * 
     * @see     java.lang.Thread#run() 
     */  
    public abstract void run();  
}  

Callable

Callable与Runnable的功能大致相似,Callable中有一个call()函数,但是call()函数有返回值。Callable的声明如下 :

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;  
}  

可以看到,这是一个泛型接口,call()函数返回的类型就是客户程序传递进来的V类型。
不同之处:
1.Callable可以返回一个类型V,而Runnable不可以;
2.Callable能够抛出checked exception,而Runnable不可以;
3.Runnable是自从java1.1就有了,而Callable是1.5之后才加上去的;
4.Callable和Runnable都可以应用于executors。而Thread类只支持Runnable;
Callable与executors联合在一起,在任务完成时可立刻获得一个更新了的Future;而Runable却要自己处理。
上面只是简单的不同,其实这两个接口在用起来差别还是很大的。

猜你喜欢

转载自blog.csdn.net/xiaomingdetianxia/article/details/77774537