如何在您正在使用的函数之外启动一个函数
How to start a function outside the function you are working in
我还是 Java 的新手,我想知道如何实现这种情况。我有一个执行某些计算的函数,完成后我想将结果传递给另一个函数,以便它可以发送通知。
我的问题是第二个函数似乎导致程序等待响应,尽管它是一个无效函数。结果,我的程序需要时间 return 结果,因为它正在执行另一个应该独立的任务。
这里有一些 sudo 代码来解释我正在尝试做的事情:
public class MyCalculationclass {
public String PerformCalculations (Object object){
// perform calculation
sendNotificationToUser(usernotificationToken, calculationValue)
return "Success"
}
public void sendNotificationToUser(String usernotificationToken,String calculationValue ){
// send user the notification
}
}
我想在我的计算完成时通知 void 函数到 运行,这样我就不必等待 void 函数到 运行 才能获得成功信息。我怎样才能在 java.
中实现这一点
使用线程:
new Thread(() -> sendNotificationToUser(usernotificationToken, calculationValue)).start();
改为
sendNotificationToUser(usernotificationToken, calculationValue);
要正确使用线程,您应该考虑创建一个 executor service:
public class MyCalculationclass {
private final ExecutorService executorService = Executors.newCachedThreadPool();
public String PerformCalculations (Object object){
// perform calculation
executorService.execute(() ->
sendNotificationToUser(usernotificationToken, calculationValue));
return "Success"
}
public void sendNotificationToUser(String usernotificationToken,String calculationValue ){
// send user the notification
}
}
稍后,您可能希望将 execute()
替换为 submit()
以获得 Future object. Or even better, use a CompletableFuture。
我还是 Java 的新手,我想知道如何实现这种情况。我有一个执行某些计算的函数,完成后我想将结果传递给另一个函数,以便它可以发送通知。
我的问题是第二个函数似乎导致程序等待响应,尽管它是一个无效函数。结果,我的程序需要时间 return 结果,因为它正在执行另一个应该独立的任务。
这里有一些 sudo 代码来解释我正在尝试做的事情:
public class MyCalculationclass {
public String PerformCalculations (Object object){
// perform calculation
sendNotificationToUser(usernotificationToken, calculationValue)
return "Success"
}
public void sendNotificationToUser(String usernotificationToken,String calculationValue ){
// send user the notification
}
}
我想在我的计算完成时通知 void 函数到 运行,这样我就不必等待 void 函数到 运行 才能获得成功信息。我怎样才能在 java.
中实现这一点使用线程:
new Thread(() -> sendNotificationToUser(usernotificationToken, calculationValue)).start();
改为
sendNotificationToUser(usernotificationToken, calculationValue);
要正确使用线程,您应该考虑创建一个 executor service:
public class MyCalculationclass {
private final ExecutorService executorService = Executors.newCachedThreadPool();
public String PerformCalculations (Object object){
// perform calculation
executorService.execute(() ->
sendNotificationToUser(usernotificationToken, calculationValue));
return "Success"
}
public void sendNotificationToUser(String usernotificationToken,String calculationValue ){
// send user the notification
}
}
稍后,您可能希望将 execute()
替换为 submit()
以获得 Future object. Or even better, use a CompletableFuture。