Exception in thread “http-nio-8888-exec-6” java.lang.IllegalStateException: It is illegal to call
this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
原代码
startAsync.start(new Runnable() {
//业务逻辑 开始异步处理
@Override
public void run() {
System.out.println("副线开始"+Thread.currentThread());
sayHello();
startAsync.complete();
//获取异步上下文
AsyncContext asyncContext = req.getAsyncContext();
//获取响应
ServletResponse response = asyncContext.getResponse();
try {
response.getWriter().write("hello async");
System.out.println("副线程结束"+Thread.currentThread().getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
修改后代码
startAsync.start(new Runnable() {
//业务逻辑 开始异步处理
@Override
public void run() {
System.out.println("副线开始"+Thread.currentThread());
sayHello();
//获取异步上下文
AsyncContext asyncContext = req.getAsyncContext();
//获取响应
ServletResponse response = asyncContext.getResponse();
try {
response.getWriter().write("hello async");
System.out.println("副线程结束"+Thread.currentThread().getName());
startAsync.complete();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
**原因startAsync.complete(); 应该在业务逻辑处理完成后调用 **