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;
class MyCallable implements Callable<Integer> {
private Integer number;
public MyCallable(Integer number) {
this.number = number;
}
@Override
public Integer call() throws Exception {
Integer sum = 0;
for (int x = 1; x <= number; x++) {
sum += x;
}
return sum;
}
}
class Mycallable implements Callable<String> {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
return null;
}
}
class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建线程池对象
ExecutorService pool = Executors.newFixedThreadPool(2);
// 可以执行 Runnable 或者 Callable 对象代表的线程
Future<Integer> future1 = pool.submit(new MyCallable(100));
Future<Integer> future2 = pool.submit(new MyCallable(200));
// TODO: 16/7/19
Integer i1 = future1.get();
Integer i2 = future2.get();
System.out.println(i1);
System.out.println(i2);
// 结束
pool.shutdown();
}
}
线程callable方法
最新推荐文章于 2024-06-22 19:09:48 发布