版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Amelia__Liu/article/details/82186443
Java5新增了Callable接口获得线程的返回值
实现Callable接口
import java.util.concurrent.Callable;
public class MyThread2 implements Callable<String> {
@Override
public String call() throws Exception {
String string="通过实现Callable借口返回";
return string;
}
}
这样调用
public static void main(String[] args) {
ExecutorService executorService=Executors.newCachedThreadPool();
Callable<String> callable=new MyThread2();
Future future=executorService.submit(callable);
try {
if(future.isDone()){
System.out.println(future.get());
}
} catch (Exception e) {
e.printStackTrace();
}
}
必须使用ExecutorService的submit方法来执行,返回一个Future对象
可以使用isDone()方法检测future是否完成,完成后可以调用get()方法获得future的
值, 如果直接调用get()方法,get()方法将阻塞值线程结束