我正在尝试调用返回Future Object的异步方法,我认为它将打印YYY,然后是XXX,因为XXX在一个1秒长的方法中。然而,在部署代码后,它不能正常工作,我用10个对象尝试了同样的事情,它们按顺序打印。错误在哪里?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testfuture;
import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.ejb.Asynchronous;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
@Singleton
@TransactionManagement(TransactionManagementType.BEAN)
public class TestFuture {
@Schedule(minute = "*/1", hour = "*", persistent = false)
public void start() {
try{
Future<String> r = inparallelMethod(5) ;
System.out.print("YYY");
r.get();
}
catch ( InterruptedException ie )
{
System.out.print(ie.getMessage());
}
catch (ExecutionException e)
{
System.out.print(e.getMessage());
}
}
@Asynchronous
public Future<String> inparallelMethod(int i) throws InterruptedException
{
Thread.sleep(1000);
System.out.print("XXX");
return null;
}
}发布于 2019-08-22 22:53:46
因为你在实例化的类中“通过”容器管理调用异步方法来调用inparallelMethod。
您必须在另一个bean中定义异步方法,@Inject该bean并调用该方法。
@Singleton
@TransactionManagement(TransactionManagementType.BEAN)
public class TestFuture {
@Inject
AsyncService service;
@Schedule(minute = "*/1", hour = "*", persistent = false)
public void start() {
try{
Future<String> r = service.inparallelMethod(5) ;
System.out.print("YYY");
r.get();
}
catch ( InterruptedException ie )
{
System.out.print(ie.getMessage());
}
catch (ExecutionException e)
{
System.out.print(e.getMessage());
}
}
}
@Stateless
public class AsyncService {
@Asynchronous
public Future<String> inparallelMethod(int i) throws InterruptedException
{
Thread.sleep(1000);
System.out.print("XXX");
return null;
}
}我张贴的代码使异步工作,但你的代码在非常差的测试异步方案,在java-ee内的Thread.sleep是一个非常糟糕的做法,因为线程是由容器管理的,你不知道哪个线程你真的在睡觉!
https://stackoverflow.com/questions/57558410
复制相似问题