Callable接口与Runable接口的区别:
(1).Callable规定的方法是call(),而Runnable规定的方法是run()
(2).Callable的任务执行后可返回值,而Runnable的任务是不能有返回值的
(3).call()方法可抛出异常,而run()方法是不能抛出异常的
(4).运行Callable任务可拿到一个Future对象
class Task implements Callable<Integer> {
public static void main(String[] args) throws OutOfMemoryError {
try {
execute();
} catch (Throwable e) {
System.out.println(e.getMessage());
}
}
/**
* execute
*
* @throws Exception
*/
public static void execute() throws Exception {
Task task = new Task();
// 线程1
Future<Integer> ft1 = new FutureTask<>(task);
new Thread((Runnable) ft1, "苦力1").start();
// 线程2
Future<Integer> ft2 = new FutureTask<>(task);
new Thread((Runnable) ft2, "苦力2").start();
// 获取线程1的最终执行返回值
System.out.println("苦力1最终的返回值是:" + ft1.get());
// 获取线程2的最终执行返回值
System.out.println("苦力2最终的返回值是:" + ft2.get());
}
@Override
public Integer call() throws Exception {
int i = 0;
int j = (new Random()).nextInt(5) + 5;
for (; i < j; i++) {
long threadId = Thread.currentThread().getId();
String threadName = Thread.currentThread().getName();
System.out.println("线程id:" + threadId + ",线程名称:" + threadName + ",正在循环,i等于" + i);
}
return i;
}
}