返回结果线程—等待单个线程(搬迁至此)

Callable接口与future类相结合可以实现future模式,Future模式在请求发生时,会产生一个Future对象给请求方,Future对象作用类似于代理,所代理的真实任务在另一个线程中继续进行,真实任务完成之后把结果放在future对象中。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestFuture {
public static void main(String[] args) throws InterruptedException, ExecutionException{
final ExecutorService exec=Executors.newFixedThreadPool(3);
Callable<String> call=new Callable<String>(){
public String call(){
try {
Thread.sleep(1000*2);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return "Thread is finished";

}
};
Future<String> task=exec.submit(call);
System.out.println("waite son Thread finished");
String obj=task.get();
System.out.println("return finished:"+obj);
exec.shutdown();
}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章