jakarta ee Asynchronous vs new Thread需要解决方案帮助(Java)
我有一个方法,目前需要返回一个结果给客户端不慢于目前。所以它必须调用一个方法并忘记它,它应该继续处理,而不是等待该方法返回任何结果。 我一直在玩ejb@Asynchronous annotation,还使用了新线程。我发现:
方法1:使用@Asynchronous——调用此方法时,调用方似乎在等待。这个方法返回void,所以我以为调用者会调用它并继续,但事实并非如此。 呼叫方代码:
public static void main(String[] args) {
System.out.println("Caller Starting");
Processor p = new Processor();
p.doSomeStuff();
System.out.println("Caller Ended");
}
public class Processor{
@Asynchronous
public void doSomeStuff() {
System.out.println("Async start");
for(int i = 0; i < 50; i++) {
System.out.println("Async: " +i);
}
System.out.println("Async ended");
}
}
方式2:使用新线程-当我这样做时,它会做我想让它做的事情
public static void main(String[] args) {
System.out.println("Caller Starting");
Processor p = new Processor();
p.doSomeStuff();
System.out.println("Caller Ended");
}
@Stateless
公共类处理器扩展线程{
public void doSomeStuff() {
start();
}
@Override
public void run() {
// Loop for ten iterations.
for(int i=0; i<10; i++) {
System.out.println(i + " looping ...");
// Sleep for a while
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// Interrupted exception will occur if
// the Worker object's interrupt() method
// is called. interrupt() is inherited
// from the Thread class.
break;
}
}
}
我是否错误地使用了@Asynchronous注释
对于这个要求,什么是好的解决方案?有没有更好更简单的方法来满足这些要求
# 1 楼答案
使用@Asynchronous注释与创建新线程时做的事情相同,但麻烦更少。在您的情况下,您一直在错误地使用注释。 异步方法必须位于无状态bean中,才能在调用方方法不等待的情况下运行。 所以也许这应该行得通