java Future 多线程并发执行
package future;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureTest {
private static int count = 0;
private final static ExecutorService _executorService = Executors.newCachedThreadPool();
/**
* @param args
*/
public static void main(String[] args) {
int num = 10;
ArrayList<Future<String>> futures = new ArrayList<Future<String>>(num);
for (int i = 0; i < num; i++) {
futures.add((Future<String>) _executorService.submit(new Callable<String>() {
public String call() throws Exception {
String res = doSomething("sdf ");
return res;
}
}));
}
try {
for (Future<String> ft : futures) {
ft.get();
}
for (Future<String> ft : futures) {
ft.cancel(true);
}
futures.clear();
_executorService.shutdown();
System.out.println(count);
} catch (Exception e) {
System.out.println("ft.get() error:" + e);
e.printStackTrace();
}
}
public static String doSomething(String str) {
count++;
return str + " is over!";
}
}