Java多线程,将多个查询并行执行

心随自在飞 2019-05-05 07:43:45

例如一个数据查询接口,需要一次查五个表的数据,

通常我们都是查出第一个后,才查第二个,。。。
这是串行,
为提高接口返回效率,让五个并行,

五个查询完毕后,再合一起做个简单的逻辑处理。
最后统一返回,这种多线程怎么写?


多线程这块不是很熟悉。
在网上看了一下 FutureTask 和 ThreadpoolExecutor 的资料,越看越迷茫。

项目用的spring boot

请教大家有没有类似的示例代码。谢谢!
...全文
2717 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
li905663280 2019-05-11
  • 打赏
  • 举报
回复
心随自在飞 2019-05-10
  • 打赏
  • 举报
回复
引用 2 楼 对梦想的牵挂 的回复:
这是之前的一个论坛上的代码,我觉得可以用在楼主这:


final CountDownLatch latch = new CountDownLatch(5);
ExecutorService threadPool = Executors.newFixedThreadPool(5);
List<Future<String>> futureTaskList = new ArrayList<Future<String>>(5);
for (int i = 0; i < 5; i++) {
futureTaskList.add(threadPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
latch.countDown();
return "ok...";
}
}));
}
try {
latch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}

try {
for (Future<String> future : futureTaskList) {
System.out.println(future.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}



多谢,就是要这段代码。


非常感谢!、




对梦想的牵挂 2019-05-06
  • 打赏
  • 举报
回复 1
这是之前的一个论坛上的代码,我觉得可以用在楼主这:

final CountDownLatch latch = new CountDownLatch(5);
ExecutorService threadPool = Executors.newFixedThreadPool(5);
List<Future<String>> futureTaskList = new ArrayList<Future<String>>(5);
for (int i = 0; i < 5; i++) {
futureTaskList.add(threadPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
latch.countDown();
return "ok...";
}
}));
}
try {
latch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}

try {
for (Future<String> future : futureTaskList) {
System.out.println(future.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
vwv泡泡鱼 2021-11-03
  • 举报
回复
@对梦想的牵挂 这个查询语句都不同,难道都放在call方法里面嘛
勇敢牛牛_ 2019-05-05
  • 打赏
  • 举报
回复
用cyclicibarrier

67,550

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧