Runnable是执行工作的独立任务,但是它不返回任何值。如果希望任务在完成的同时能够返回一个值,可以通过实现Callable接口。在JDK5.0中引入的Callable接口是一种具有类型参数的泛型,它的类型参数表示从方法call中返回的值的类型。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Demo05 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable<Integer> callable = new Demo05Callable();
FutureTask<Integer> task = new FutureTask<>(callable);
Thread t1 = new Thread(task);
t1.start();
System.out.println("线程返回的值是:" + task.get());
}
}
class Demo05Callable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName() + "调用了callable接口的实现类");
int val = (int)(Math.random() * 10);
System.out.println("准备返回的值是:" + val);
return val;
}
}