Callable类实现简单的异步运算
代码如下:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by Aongi on 2017/4/30.
* Version 1.0
*/
public class ThreadPool {
//main方法
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService es= Executors.newFixedThreadPool(2);
System.out.println(es.submit(new ThreadPoolRunnable(100)).get());
System.out.println(es.submit(new ThreadPoolRunnable(200)).get());
es.shutdown();
}
}
线程类:
import java.util.concurrent.Callable;
/**
* Created by Aongi on 2017/4/30.
* Version 1.0
*/
public class ThreadPoolRunnable implements Callable {
int a;
public ThreadPoolRunnable(int a) {
this.a = a;
}
@Override
public Object call() throws Exception {
int num = 0;
for (int i = 1; i <= a; i++) {
num = num + i;
}
return num;
}
}