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;
/**
* 这个类主要展示Future的使用,可以用它来提交一些需要时间较长的任务,然后系统就可以去做其它工作了
* 完成其它工作后再取得结果,如果结果仍未完成,会阻塞等待!
* @author Administrator
*
*/
public class FutureTest {
private static final ExecutorService exec=Executors.newFixedThreadPool(10);
public static void main(String[] args) {
System.out.println("main start.......");
Callable<String> task=new Callable<String>() {
public String call() throws Exception {
Thread.sleep(5000);
return "王法波";
}
};
System.out.println("after task created....");
System.out.println("submit task....");
Future <String>future=exec.submit(task);//提交任务
long start=System.nanoTime();
System.out.println("提交任务后可以继续执行,即使任务未完成....."+(System.nanoTime()-start));//进行其它工作
try {
String str=future.get();
System.out.println(str);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("被阻塞"+(System.nanoTime()-start)+"毫微秒");
exec.shutdown();
}
}