提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
Future和FutureTask的区别
请看文章:https://blog.csdn.net/m0_37148920/article/details/98885859
一、单线程调用
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
Random random = new Random(100);
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return random.nextInt(10);
}
};
FutureTask<Integer> futureTask = new FutureTask<>(callable);
new Thread(futureTask).start();
System.out.println(futureTask.get());
}
}
二、线程池调用
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
ExecutorService executorService = Executors.newCachedThreadPool();
Random random = new Random(100);
for (int i = 0; i < 10; i++) {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return random.nextInt(10);
}
};
FutureTask<Integer> futureTask = new FutureTask<>(callable);
executorService.submit(futureTask);
}
}
}
三、批量获取线程池执行结果
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
List<FutureTask<Integer>> list = new ArrayList<>();
ExecutorService executorService = Executors.newCachedThreadPool();
Random random = new Random(100);
for (int i = 0; i < 10; i++) {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return random.nextInt(10);
}
};
FutureTask<Integer> futureTask = new FutureTask<>(callable);
executorService.submit(futureTask);
}
list.forEach( x -> {
try {
System.out.println(x.get());
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
});
}
}