下面来看另一种方式使用Callable和Future,通过ExecutorService的submit方法执行Callable,并返回Future,代码如下:
[java] [view plain](() [copy](() [print](() [?](() [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1bArfsGD-1652074444137)(https://code.youkuaiyun.com/assets/CODE_ico.png)] [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8SGAzhTQ-1652074444137)(h 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 ttps://code.youkuaiyun.com/assets/ico_fork.svg)]
-
public class CallableAndFuture {
-
public static void main(String[] args) {
-
ExecutorService threadPool = Executors.newSingleThreadExecutor();
-
Future future = threadPool.submit(new Callable() {
-
public Integer call() throws Exception {
-
return new Random().nextInt(100);
-
}
-
});
-
try {
-
Thread.sleep(5000);// 可能做一些事情
-
System.out.println(future.get());
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
} catch (ExecutionException e) {
-
e.printStackTrace();
-
}
-
}
-
}
代码是不是简化了很多,ExecutorService继承自Executor,它的目的是为我们管理Thread对象,从而简化并发编程,Executor使我们无需显示的去管理线程的生命周期,是JDK 5之后启动任务的首选方式。
执行多个带返回值的任务,并取得多个返回值,代码如下:
[java] [view plain](() [copy](() [print](() [?](() [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RdaiBZBc-1652074444138)(https://code.youkuaiyun.com/assets/CODE_ico.png)] [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dZPR9iTd-1652074444138)(https://code.youkuaiyun.com/assets/ico_fork.svg)]
-
public class CallableAndFuture {
-
public static void main(String[] args) {
-
ExecutorService threadPool = Executors.newCachedThreadPool();
-
CompletionService cs = new ExecutorCompletionService(threadPool);
-
for(int i = 1; i < 5; i++) {
-
final int taskID = i;
-
cs.submit(new Callable() {
-
public Integer call() throws Exception {
-
return taskID;
-
}
-
});
-
}
-
// 可能做一些事情
-
for(int i = 1; i < 5; i++) {
-
try {
-
System.out.println(cs.take().get());
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
} catch (ExecutionException e) {
-
e.printStackTrace();
. } catch (ExecutionException e) { -
e.printStackTrace();