Callable和Future创建线程
Callable是一个接口,而且还是一个函数式接口
@FunctionalInterface
public interface Callable
该接口有一个call()方法,call方法和run方法是有区别的,最主要的区别是call方法是有返回值的,call返回会抛出异常的
future接口
Interface Future
我们先看看怎么创建线程
thread的构造方法
可以看出Thread的构造方法是没有Callable的,所以无法通过
new Thread(Callable)创建线程的。
看一看Runnable有哪些实现类
现在来看看FutureTask这个类
实现了Future和Runnable接口
通过这样层层的描述,那么我们就可以这样创建线程了
1.写一个类实现Callable接口,重写里面的call方法,比如这个类是T
2.创建一个FutureTask对象,比如 new FutureTask(T );
3.new Thread(new FutureTask(T ));
代码实现:
public class CallThreadTest {
public static void main(String[] args) {
CallThread t= new CallThread();
FutureTask<Integer> integerFutureTask = new FutureTask<>(t);
Thread thread = new Thread(integerFutureTask);
thread.start();
try {
//获取call方法返回的值,call方法会抛出异常,所以这里需要捕获一下
Integer integer = integerFutureTask.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
static class CallThread implements Callable<Integer>{
//重写call方法,call方法和run方法还有有几点区别的,最大的区别就是call方法有返回值
@Override
public Integer call() throws Exception {
return 12345;
}
}
}