- * 目的:了解callable、future
- *
- */
- public class CallableAndFutureTest {
- public static void main(String[] args) {
-
- //ExecutorService singlePool = Executors.newSingleThreadExecutor();
-
- /**
- * Callable有返回值,而且会抛异常
- * 在线程池中用submit调用,返回一个Future
- */
- /*Future<String> future =
- singlePool.submit(new Callable<String>(){
- public String call() throws Exception {
- Thread.sleep(2000);
- return "hello";
- }
-
- });
-
- try {
- System.out.println(future.get()); //通过get()方法得到结果
- System.out.println(future.get(1, TimeUnit.SECONDS)); //如果多少秒还没得到结果就抛异常
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (TimeoutException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }*/
- ExecutorService pool = Executors.newFixedThreadPool(3);
- /**
- * 等到一组Future,谁先返回,谁先加入到CompletionService的队列中
- */
- CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(pool);
- for(int i=0;i<10;i++){
- final int num = i;
- completionService.submit(new Callable<Integer>() {
- public Integer call() throws Exception {
- System.out.println("callable now is"+num);
- return num;
- }
- });
- }
- for(int i=0;i<10;i++){
- try {
- System.out.println(completionService.take().get());
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- }
- }
- }
- }
复制代码 |
|