转载自: http://auguslee.iteye.com/blog/1292335
Callable 和 Runnable 的使用方法大同小异, 区别在于:
1.Callable 使用 call() 方法, Runnable 使用 run() 方法
2.call() 可以返回值, 而 run()方法不能返回。
3.call() 可以抛出受检查的异常,比如ClassNotFoundException, 而run()不能抛出受检查的异常。
Callable示例如下:
执行结果
Runnable示例:
执行结果
注意ExecutorService 在Callable中使用的是submit(), 在Runnable中使用的是 execute()
1.Callable 使用 call() 方法, Runnable 使用 run() 方法
2.call() 可以返回值, 而 run()方法不能返回。
3.call() 可以抛出受检查的异常,比如ClassNotFoundException, 而run()不能抛出受检查的异常。
Callable示例如下:
class TaskWithResult implements Callable<String> {
private int id;
public TaskWithResult(int id) {
this.id = id;
}
@Override
public String call() throws Exception {
return "result of TaskWithResult " + id;
}
}
public class CallableTest {
public static void main(String[] args) throws InterruptedException,
ExecutionException {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>(); //Future 相当于是用来存放Executor执行的结果的一种容器
for (int i = 0; i < 10; i++) {
results.add(exec.submit(new TaskWithResult(i)));
}
for (Future<String> fs : results) {
if (fs.isDone()) {
System.out.println(fs.get());
} else {
System.out.println("Future result is not yet complete");
}
}
exec.shutdown();
}
}
执行结果
Runnable示例:
public class LiftOff implements Runnable {
protected int countDown = 10;
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOff() {
}
public LiftOff(int countDown) {
this.countDown = countDown;
}
public String status() {
return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff! ") + ")";
}
@Override
public void run() {
while (countDown-- > 0) {
System.out.print(status());
Thread.yield();
}
System.out.println();
}
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(1);
for (int i = 0; i < 5; i++) {
exec.execute(new LiftOff());
}
exec.shutdown();
}
}
执行结果
注意ExecutorService 在Callable中使用的是submit(), 在Runnable中使用的是 execute()