第一种情况,Service类:
@Async public String test1() { String threadName = Thread.currentThread().getName(); log.error("{}: 1 start", threadName); try { Thread.sleep(5000L); } catch (Exception e){ } log.error("{}: 1 end", threadName); return "s1"; } @Async public String test2() { String threadName = Thread.currentThread().getName(); log.error("{}: 2 start", threadName); try { Thread.sleep(2000L); } catch (Exception e){ } log.error("{}: 2 end", threadName); return "s2"; }
Controller类:
try { String threadName = Thread.currentThread().getName(); log.error("{}: 0 start", threadName); PrintWriter out = response.getWriter(); String f1 = testService.test1(); String f2 = testService.test2(); log.error("{}: 0 end {} {}", threadName, f1, f2); } catch (Exception e) { }
结果是,test1和test2在不同线程被执行,然而对test1和test2的调用,立刻结束,f1和f2都是null。
也就是说,这样可以独立执行两个后台任务,然而并不能等待返回结果,怎样才能得到结果呢?
第二种情况,Service类:
@Async public Future<String> test1() { String threadName = Thread.currentThread().getName(); log.error("{}: 1 start", threadName); try { Thread.sleep(5000L); } catch (Exception e){ } log.error("{}: 1 end", threadName); return new AsyncResult<>("s1"); } @Async public Future<String> test2() { String threadName = Thread.currentThread().getName(); log.error("{}: 2 start", threadName); try { Thread.sleep(2000L); } catch (Exception e){ } log.error("{}: 2 end", threadName); return new AsyncResult<>("s2"); }
Controller类:
try { String threadName = Thread.currentThread().getName(); log.error("{}: 0 start", threadName); PrintWriter out = response.getWriter(); Future<String> f1 = testService.test1(); Future<String> f2 = testService.test2(); log.error("{}: 0 end {} {}", threadName, f1.get(), f2.get()); } catch (Exception e) { }
这样可以正确得到结果。Futrue<T>和AsyncResult<T>让调用线程可以join,等待Future结果。
发表回复
要发表评论,您必须先登录。