Runnable和Callable之间的区别

1、Runnable任务执行后没有返回值;Callable任务执行后可以获得返回值

2、Runnable的方法是run(),没有返回值;Callable的方法是call(),有返回值

3、Runnable的run()方法不能抛异常,有异常的话只能在run方法里面解决;Callable的call()方法可以抛异常

4、Runnable可以直接传递给Thread对象执行;Callable不可以,Callable执行可以放在FutureTask中,然后把futureTask传递给Thread执行

这里只关注了异常的捕捉:

package com.qjc.thread.runandcall;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask; public class RunnableAndCallable { public static void main(String[] args) {
// Runnable可以直接传递给Thread对象执行
new Thread(new RunnableThread()).start();
// 查看FutureTask源码最终集继承是Runnable, Future<V>接口,所以可通过Excutor(线程池) 来执行,也可传递给Thread对象执行。
FutureTask<String> futureTask = new FutureTask<>(new CallableThread());
new Thread(futureTask).start();
String string = null;
try {
string = futureTask.get();
} catch (InterruptedException e) {
string = "InterruptedException";
e.printStackTrace();
} catch (ExecutionException e) {
string = "ExecutionException";
e.printStackTrace();
}
System.out.println("CallableThread输出:" + string);
}
} class RunnableThread implements Runnable {
@Override
public void run() {
int a = 0;
try {
a = 100 / 0;
System.out.println("RunnableThread输出:" + a);
} catch (Exception e) {
System.err.println("RunnableThread出异常了");
e.printStackTrace();
}
}
} class CallableThread implements Callable<String> {
@Override
public String call() throws Exception {
int a = 100 / 1;
return String.valueOf(a);
}
}
05-08 08:28