public class Demo {
public static void main(String[] args) {
// 创建一个线程池
ExecutorService service = Executors.newCachedThreadPool();
// 穿件一个Future对象接受线程返回值
Future<Integer> result = service.submit(new Callable() {
int sum = 0;
@Override
public Object call() throws Exception {
for (int i = 0; i <= 100; i++) {
sum += i;
}
return sum;
}
});
try {
System.out.println("最后的结果是:" + result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// 关闭线程池
service.shutdown();
}
} |
|