简体   繁体   English

我可以同时运行 2 个线程并在 java 上设置一个结果吗?

[英]Can I run 2 threads same time and set one Result on java?

I want create 2 threads and run them both at the same time.我想创建 2 个线程并同时运行它们。 I want put condition that if the first thread answer data null or empty I want set the other thread response (it can be null or empty I don't need put restriction).我想设置条件,如果第一个线程回答数据 null 或空我想设置另一个线程响应(它可以是 null 或空我不需要限制)。 How can I do it, any suggestions?我该怎么做,有什么建议吗? I want it to do in Spring Framework.我希望它在 Spring 框架中执行。

You could set an environment variable and if not a global variable maybe stuff into a control file that each thread could read.您可以设置一个环境变量,如果不是全局变量,则可能会填充到每个线程可以读取的控制文件中。 Or even a data base entry.甚至是数据库条目。

you could try CompletableFuture, eg你可以试试 CompletableFuture,例如

CompletableFuture<String> future1  
  = CompletableFuture.supplyAsync(() -> firstApi());
CompletableFuture<String> future2  
  = CompletableFuture.supplyAsync(() -> secondApi());

CompletableFuture<Void> combinedFuture 
  = CompletableFuture.allOf(future1, future2);

// wait for completion
combinedFuture.get();

// check and return results, e.g.
String result1 = future1.get();
if(null == result1) {
  return future2.get();
}
return result1;

https://www.baeldung.com/java-completablefuture https://www.baeldung.com/java-completablefuture

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM