package cn.itcast.hemai2;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Future设计模式
* @author admin
*
*/
public class CallableAndFuture {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
// threadPool.submit(null);如果需要这个线程的请求返回数据用submit,如果不需要用exe....
Future<String> future = threadPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {//call方法执行实际工作内容和返回对象
Thread.sleep(2000);
return "hello";
}
});
System.out.println("等待结果 ");//在等待结果时间,此时可以处理其它的业务逻辑。
try {
System.out.println("Future模式在处理了其它的业务逻辑后得到结果 "+future.get());
System.out.println("Future模式在处理了其它的业务逻辑后得到结果 "+future.get(3,TimeUnit.SECONDS));//超过一秒得不到结果,就抛出异常。
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
System.out.println("TimeoutException");
e.printStackTrace();
}
//批量提交任务,并且得到每个任务返回的结果,一旦获得就显示出来 。
ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2) ;
for (int i = 0; i < 10; i++) {
final int seq = i;
completionService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(new Random().nextInt(5000));
return seq;
}
});
}
for (int i = 0; i < 10; i++) {
try {
System.out.println(completionService.take().get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
http://www.blogjava.net/shinzey/archive/2011/09/29/359781.html
http://www.thebigdata.cn/JiShuBoKe/4914.html