开启十条线程,第一个1到10想加,第二个11到20想加,以次类推 得到结果并输出
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- public class Demo {
- public static void main(String[] args) throws Exception, Exception {
- ExecutorService es = Executors.newFixedThreadPool(10);
- Future<Integer> f1 = es.submit(new MyCallable(1,10));
- Future<Integer> f2 =es.submit(new MyCallable(11,20));
- Future<Integer> f3 =es.submit(new MyCallable(21,30));
- Future<Integer> f4 =es.submit(new MyCallable(31,40));
- Future<Integer> f5 =es.submit(new MyCallable(41,50));
- Future<Integer> f6 =es.submit(new MyCallable(51,60));
- Future<Integer> f7 =es.submit(new MyCallable(61,70));
- Future<Integer> f8 =es.submit(new MyCallable(71,80));
- Future<Integer> f9 =es.submit(new MyCallable(81,90));
- Future<Integer> f10 =es.submit(new MyCallable(91,100));
- System.out.println(f1.get());
- System.out.println(f2.get());
- System.out.println(f3.get());
- System.out.println(f4.get());
- System.out.println(f5.get());
- System.out.println(f6.get());
- System.out.println(f7.get());
- System.out.println(f8.get());
- System.out.println(f9.get());
- System.out.println(f10.get());
-
- es.shutdown();
-
- }
- }
- class MyCallable implements Callable<Integer>{
- private int start;
- private int end;
-
- public MyCallable(int start,int end){
- this.start=start;
- this.end=end;
- }
-
- public Integer call() throws Exception{
-
- int sum=0;
- for(;start<=end;start++){
- sum+=start;
- }
- return sum;
-
- }
- }
复制代码 |
|