A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© z_one 中级黑马   /  2015-11-10 21:44  /  274 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


package concurrentThread;
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;
public class CallableAndFuture {
public static void main(String[] args) throws InterruptedException,
   ExecutionException {
  ExecutorService pool = Executors.newFixedThreadPool(10);
  CompletionService<Boolean> exchangeResult = new ExecutorCompletionService<Boolean>(
    pool);
  for (int i = 1; i <= 10; i++) {
   exchangeResult.submit(new TaskWorker(i)) ;  //这里会报错,请问为什么呢?
  }
  for (int i = 0; i < 10; i++) {
   System.out.println(exchangeResult.take().get());
  }
  try {
   for (int j = 0; j < 10; j++) {
    Future<Boolean> future = exchangeResult.take();
    if (future.get() == true)
     System.out.println(" exchange thread " + j + " succeed!");
    else
     System.out.println(" exchange thread " + j + " fail!");
   }
  } catch (InterruptedException e) {
   e.printStackTrace();
  } catch (ExecutionException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
  pool.shutdown() ;
}
private class TaskWorker implements Callable<Boolean> {
  int i = 0;
  public TaskWorker(Integer i) {
   this.i = i;
  }
  @Override
  public Boolean call() throws Exception {
   System.out.println(Thread.currentThread().getName() + " get " + i);
   return true;
  }
}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马