多线程实现第三种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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   LoaderMan  阅读(384)  评论(0编辑  收藏  举报

努力加载评论中...

导航

点击右上角即可分享
微信分享提示