(1)@Async
@Test
public void test3() throws Exception {
System.out.println("main函数开始执行"); 1
myService.longtime(); 3....
System.out.println("main函数执行结束"); 2
}
@Async
public void longtime() {
System.out.println("我在执行一项耗时任务");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("完成");
}
(2)AsyncResult
如果需要返回值,耗时方法返回值用AsyncResult包装。
@Test
public void test4() throws Exception {
System.out.println("main函数开始执行");
Future future=myService.longtime2();
System.out.println("main函数执行结束");
System.out.println("异步执行结果:"+future.get());
}
@Async
public Future longtime2() {
System.out.println("我在执行一项耗时任务");
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("完成");
return new AsyncResult<>(3);
}
@Asyn异步编程
最新推荐文章于 2024-10-11 09:37:52 发布