FutureTask类图如下所示:(适配器模式)
图1-1 FutureTask类图.pngCallable接口示例代码如下所示:
/**
* @author luffy
**/
public class CallableTest {
public static void main(String[] args){
FutureTask<Integer> task1 = new FutureTask<>(new ThreadTest());
//FutureTask<Integer> task2 = new FutureTask<>(new ThreadTest());
Thread t1 = new Thread(task1,"AA");
Thread t2 = new Thread(task1,"BB"); //复用
t1.start();
t2.start();
while (!task1.isDone()){
}
try {
int res = task1.get(); //一般放在最后-要求获得Callable线程的结果,如果没有计算完则阻塞,直到计算完成
System.out.println(res);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
class ThreadTest implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName()+":come in!");
return 1024;
}
}
网友评论