异步与新线程-需要帮助的解决方案(Java)

时间:2019-07-13 09:26:02

标签: java java-ee ejb-3.1

我有一个方法,当前需要将结果返回给客户端的速度不比现在慢。因此,它必须调用一个方法并忘记它,它应该继续处理而不要等待该方法返回任何结果。 我一直在玩ejb @Asynchronous批注,也使用新的线程。我发现了以下内容:

方法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 个答案:

答案 0 :(得分:1)

使用@Asynchronous注释与创建新线程时具有相同的作用,但麻烦较少。在您的情况下,您使用的注释不正确。 异步方法必须在无状态Bean中,才能在不等待调用方方法等待的情况下运行。 因此,这可能应该可行,

@Stateless
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");
}