Callable接口和Runnable接口相似,区别就是Callable需要实现call方法,而Runnable需要实现run方法;并且,call方法有返回值。
Runnable是执行工作的独立任务,不具有返回值。在Java SE5中引入的Callable是一种具有;类型参数的泛型,参数类型为从方法call()中返回的值,并且必须使用ExecutorService.submit()调用它。
Runnable和Callable都是接口
不同之处:
1.Callable可以返回一个类型V,而Runnable不可以
2.Callable能够抛出checked exception,而Runnable不可以。
Callable的源码如下:
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;
}
Runnable的源码如下:
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();
}
import java.util.*;
import java.util.concurrent.*;
public class CallableDemo {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList> listResult = new ArrayList>();
for (int i = 0; i < 5; i++) {
listResult.add(exec.submit(new Calls(i)));
}
for(Future fs:listResult)
try {
System.out.println(fs.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Calls implements Callable{
private int id;
public Calls() {
}
public Calls(int id) {
this.id = id;
}
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
return "the current id is: "+this.id;
}
}