Callable实现方法
1、示例代码如下:
package com.jh.www;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Demo6 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//创建线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//往线程池中放线程
Future<Integer>f1 =pool.submit(new MyCallable(100));
Future<Integer>f2 =pool.submit(new MyCallable(50));
System.out.println(f1.get());
System.out.println(f2.get());
//关闭线程池
pool.shutdown();
}
}
class MyCallable implements Callable<Integer>{
private int num;
public MyCallable(int num) {
this.num = num;
}
public Integer call() throws Exception {
int sum=0;
// TODO Auto-generated method stub
for(int i =0; i<=num;i++) {
sum+=i;
}
return sum;
}
}