多线程实现第三种方式

import java.util.concurrent.Callable;

 import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

public class CallableDemo {

   public static void main(String[] args) throws Exception {

      ExecutorService pool = Executors.newFixedThreadPool(2);

       // 可以执行Runnable对象或者Callable对象代表的线程

       Future<Integer> f1 = pool.submit(new MyCallable(100));

      Future<Integer> f2 = pool.submit(new MyCallable(200));

      // V get()
       Integer i1 = f1.get();
      //

      Integer i2 = f2.get();

      //

      System.out.println(i1);

      System.out.println(i2);

       // 结束

       pool.shutdown();
   }
}
 
class MyCallable implements Callable<Integer> {

   private int number;

   public MyCallable(int number) {

      this.number = number;
   }

    public Integer call() throws Exception {
      int sum = 0;

      for (int x = 1; x <= number; x++) {

         sum += x;
 
      }
      return sum;
   }

}

 

 

posted on 2017-02-17 18:57  LoaderMan  阅读(384)  评论(0编辑  收藏  举报

导航