原理图:
特点:
- 用Callable实现的多线程,线程能有返回值
- 示例代码:
class DemoThread implements Callable {
//与实现Runnable接口一样,实现Callable接口要重写call()方法
@Override
public Object call() throws Exception {
String s = Thread.currentThread().getName();
return s;
}
}
public class ThreadCallable {
public static void main(String[] args) {
//1、实例化Callable的子类
DemoThread demo = new DemoThread();
//FutureTask包装了Callable类且间接继承了Runnable抽象类
//2、实例化一个FutureTask的对象
FutureTask f = new FutureTask(demo);
//3、将实例化的FutureTask的对象传入Thread类的构造方法,调用start()方法启动线程
new Thread(f,"我是创建的Callable线程。").start();
try {
System.out.println(f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}