英文:
multiple threads in java method
问题
我有一个方法,我想同时运行两个线程。
以下是该方法
@PostMapping(value = "/sendmails")
public ResponseEntity<Object> sendEmails(@RequestParam("file") MultipartFile reapExcelDataFile) {
bulkMailProcessor.processor(reapExcelDataFile);
return ResponseEntity.status(HttpStatus.OK).build();
}
我想运行bulkMailProcessor.processor(reapExcelDataFile);
这一行,但我不想等待邮件发送过程完成,主线程需要继续发送邮件,但另一个线程需要启动并发送结果回来。如何实现这个功能。
英文:
I have a method, I want to run two threads at a time.
The following is the method
@PostMapping(value = "/sendmails")
public ResponseEntity<Object> sendEmails(@RequestParam("file") MultipartFile reapExcelDataFile) {
bulkMailProcessor.processor(reapExcelDataFile);
return ResponseEntity.status(HttpStatus.OK).build();
}
I want to run bulkMailProcessor.processor(reapExcelDataFile);
line and I don't want to wait until the process completed of the mails sending, the main thread need to continue to send mails but another thread need to start and send the result back. How can I achieve this functionality.
答案1
得分: 2
使用CompletableFuture
。它将处理创建线程执行器、运行线程等操作。
如果你只想启动一个进程而不关心返回值,可以使用:
CompletableFuture.runAsync(() -> someConsumingCode);
如果你想将某个值返回给一个函数,可以通过链式调用API中提供的各种方法传递结果...
CompletableFuture.supplyAsync(() -> someSupplyingCode()).thenApply((outputofSomeSupplyingCode) -> consumeOutputOfSomeSupplyingCode(outputOfSomeSupplyingCode));
当你希望主线程等待结果时,可以将结果分配给一个变量,然后调用get
方法:CompletableFuture.get()
:
CompletableFuture<String> resultFuture = CompletableFuture.supplyAsync(() -> "HelloWorld");
String result = resultFuture.get();
System.out.println(result); // 输出 "HelloWorld"
英文:
Use CompletableFuture
. It will handle creating the thread executor, running the thread, etc.
If you want to just spin off a process and don't care about a return use:
CompletableFuture.runAsync(() -> someConsumingCode; );
If you want to return some value to a function you can pass the result by chaining various methods available from the api...
CompletableFuture.supplyAsync(() -> someSupplyingCode()).thenApply((outputofSomeSupplyingCode) -> consumeOutputOfSomeSupplyingCode(outputOfSomeSupplyingCode));
When you want the main thread to wait for a result you can assign the result to a variable and then call the get method: CompletableFuture.get()
:
CompletableFuture<String> resultFuture = CompletableFuture.supplyAsync(() -> "HelloWorld");
String result = resultFuture.get();
System.out.println(result); // outputs "HelloWorld"
答案2
得分: 0
使用Executors框架并继续提交任务,这是您的方法调用。它将在内部为每个任务创建新线程,并管理所有资源,而不是传统的方式,您过去常常创建线程并运行。
英文:
Use Executors Framework and keep on submitting task which is your method call. It will internally create new thread for each task and manage all the resources instead of traditional way where you used to create thread and run.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论