简体   繁体   中英

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. 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). How can I do it, any suggestions? I want it to do in Spring Framework.

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<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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