一个小练习:求和案例
package cn.itcast_04;
import java.util.concurrent.Callable;
public class MyCallable2 implements Callable<Integer> {
private int number;
public MyCallable2(int number){
this.number=number;
}
@Override
public Integer call() throws Exception {
int sum=0;
for(int x=0;x<=number;x++){
sum+=x;
}
return sum;
}
}
package cn.itcast_04;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadPool3 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool=Executors.newFixedThreadPool(2);
Future<Integer> f1=pool.submit(new MyCallable2(100));
Future<Integer> f2=pool.submit(new MyCallable2(50));
Integer i1=f1.get();
Integer i2=f2.get();
System.out.println(i1);
System.out.println(i2);
}
}
|
|