Thread类和实现Runnable接口的线程类是没有返回值的,都是重写它们的run()方法,对比这两个创建线程的方式发现,这个run()方法有不足:
1.没有返回值
2.不能抛出异常
基于上面的两个不足,在JDK1.5以后出现了第三种创建线程的方式:实现Callable接口:
实现Callable接口的好处:1.有返回值 2.能抛出异常
缺点:线程创建比较麻烦
public class MyThread implements Callable{ @Override public Integer call() throws Exception { return new Random().nextInt(10);//返回10以内的随机数 } }
测试类
public static void main(String[] args) throws ExecutionException, InterruptedException {
//定义一个线程对象
MyThread mt = new MyThread();
FutureTask ft = new FutureTask(mt);
Thread t = new Thread(ft);
t.start();
//获取线程得到的返回值:
Object obj =ft.get();
System.out.println(obj);
}



