这个接口不太常用,比起其它几种线程的创建方式,它的其中一个明显特点是可以有返回值。
一开始,我就觉得,既然是线程,因为是异步执行,那返回值岂不是没有机会拿到?
其实,从返回值类型Future可以看出,它是代表未来的值,使用场景一定是未来的某一个时刻去获取它的返回值。而且Futrue.get()方法在没有获取到返回值时会阻塞当前线程。如果你刚运行线程就尝试获取返回值,这样使用线程没有意义。
比如下面这段代码,100的打印在6秒之后,而不是11秒,如果去掉6秒的等待,那就是5秒之后获取到返回值:
package liwen.zhao.threadtest;
import java.util.concurrent.*;
class CallableTest {
public static void main(String[] args) {
System.out.println("start main");
ExecutorService executorService = Executors.newCachedThreadPool();
CallableT callThread = new CallableT();
Future future = executorService.submit(callThread);
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Object obj = future.get();
System.out.println(obj.toString());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println("end main");
}
}
class CallableT implements Callable{
@Override
public Object call() throws Exception {
Thread.sleep(5000);
return new Integer(100);
}
}