通过线程池中的线程对象,使用Callable接口完成两个数求和操作
1、l Future接口:用来记录线程任务执行完毕后产生的结果。线程池创建与使用
2、n V get() 获取Future对象中封装的数据结果
用线程池计算1..100,1...200的和
package com.oracle.demo05; import java.util.concurrent.Callable; public class MyCall implements Callable<Integer> { private int num1; private int num2; public MyCall(){} public MyCall(int num1,int num2){ this.num1=num1; this.num2=num2; } @Override public Integer call() throws Exception { int sum=0; for(int i=num1;i<=num2;i++){ sum+=i; } return sum; } }
package com.oracle.demo05; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class demo01 { // 用线程池计算1..100,1...200的和 public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService es=Executors.newFixedThreadPool(2); MyCall mc1=new MyCall(50,100); MyCall mc2=new MyCall(44,200); // 让线程池自主选择一条线程执行线程任务 Future<Integer> f1=es.submit(mc1); Future<Integer> f2=es.submit(mc2); // 获取线程任务返回值 int sum1=f1.get(); int sum2=f2.get(); System.out.println(sum1); System.out.println(sum2); } }