future_callable

Future<V>代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则,get()会使当前线程阻塞。FutureTask<V>实现了Future<V>和Runable<V>。Callable代表一个有返回值得操作。

简单代码:

public class FutureTest {
 public static class Task implements Callable<String>{
	@Override
	public String call() throws Exception {
		Thread.sleep(1800);
		System.out.println("ah");
		return "something";
	}
	
 }
 public static void main(String[] args) throws InterruptedException, ExecutionException {
	List<Future<String>> future = new ArrayList<Future<String>>();
	ExecutorService service = Executors.newCachedThreadPool();
	for (int i = 0; i < 100; i++) {
		future.add(service.submit(new Task()));			
	}
	for (Future<String> future2 : future) {
		System.out.println(future2.get());
	}
 }
}

稍微复杂: 集合里面的数和,查看cpu数量,分开开线程

public class FutureTest1 {
private ExecutorService exec;  
  private int cpuCoreNumber;  
  private List<Future<Long>> tasks = new ArrayList<Future<Long>>();
  // 内部类  
  class SumCalculator implements Callable<Long> {  
      private int[] numbers;  
      private int start;  
      private int end;  

      public SumCalculator(final int[] numbers, int start, int end) {  
          this.numbers = numbers;  
          this.start = start;  
          this.end = end;  
      }  

      public Long call() throws Exception {  
          Long sum = 0l;  
          for (int i = start; i < end; i++) {  
              sum += numbers[i];  
          }  
          return sum;  
      }  
  }  
  public FutureTest1() {  
      cpuCoreNumber = Runtime.getRuntime().availableProcessors();  
      exec = Executors.newFixedThreadPool(cpuCoreNumber);  
  }  

  public Long sum(final int[] numbers) {  
      // 根据CPU核心个数拆分任务,创建FutureTask并提交到Executor  
      for (int i = 0; i < cpuCoreNumber; i++) {  
          int increment = numbers.length / cpuCoreNumber + 1;  
          int start = increment * i;  
          int end = increment * i + increment;  
          if (end > numbers.length)  
              end = numbers.length;  
          SumCalculator subCalc = new SumCalculator(numbers, start, end);  
          FutureTask<Long> task = new FutureTask<Long>(subCalc);  
          tasks.add(task);  
          if (!exec.isShutdown()) {  
              exec.submit(task);  
          }  
      }  
      return getResult();  
  }  
  /** 
   * 迭代每个只任务,获得部分和,相加返回 
   *  
   * @return 
   */  
  public Long getResult() {  
      Long result = 0l;  
      for (Future<Long> task : tasks) {  
          try {  
              // 如果计算未完成则阻塞  
              Long subSum = task.get();  
              result += subSum;  
          } catch (InterruptedException e) {  
              e.printStackTrace();  
          } catch (ExecutionException e) {  
              e.printStackTrace();  
          }  
      }  
      return result;  
  }  

  public void close() {  
      exec.shutdown();  
  }
  
  public static void main(String[] args) {
  	int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 };  
  	FutureTest1 calc = new FutureTest1();  
  	Long sum = calc.sum(numbers);  
  	System.out.println(sum);  
  	calc.close(); 
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值