- 将
@EnableAsync
添加在spring配置类上,此时@Async
注解才会起效。
常见2种用法
-
无返回值的
-
可以获取返回值的
4、无返回值的
用法
方法返回值不是Future
类型的,被执行时,会立即返回,并且无法获取方法返回值,如:
@Async
public void log(String msg) throws InterruptedException {
System.out.println(“开始记录日志,” + System.currentTimeMillis());
//模拟耗时2秒
TimeUnit.SECONDS.sleep(2);
System.out.println(“日志记录完毕,” + System.currentTimeMillis());
}
案例
实现日志异步记录的功能。
LogService.log方法用来异步记录日志,需要使用@Async
标注
package com.javacode2018.async.demo1;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class LogService {
@Async
public void log(String msg) throws InterruptedException {
System.out.println(Thread.currentThread() + “开始记录日志,” + System.currentTimeMillis());
//模拟耗时2秒
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread() + “日志记录完毕,” + System.currentTimeMillis());
}
}
来个spring配置类,需要加上@EnableAsync
开启bean方法的异步调用.
package com.javacode2018.async.demo1;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableAsync;
@ComponentScan
@EnableAsync
public class MainConfig1 {
}
测试代码
package com.javacode2018.async;
import com.javacode2018.async.demo1.LogService;
import com.javacode2018.async.demo1.MainConfig1;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.concurrent.TimeUnit;
public class AsyncTest {
@Test
public void test1() throws InterruptedException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(MainConfig1.class);
context.refresh();
LogService logService = context.getBean(LogService.class);
System.out.println(Thread.currentThread() + " logService.log start," + System.currentTimeMillis());
logService.log(“异步执行方法!”);
System.out.println(Thread.currentThread() + " logService.log end," + System.currentTimeMillis());
//休眠一下,防止@Test退出
TimeUnit.SECONDS.sleep(3);
}
}
运行输出
Thread[main,5,main] logService.log start,1595223990417
Thread[main,5,main] logService.log end,1595223990432
Thread[SimpleAsyncTaskExecutor-1,5,main]开始记录日志,1595223990443
Thread[SimpleAsyncTaskExecutor-1,5,main]日志记录完毕,1595223992443
前2行输出,可以看出logService.log
立即就返回了,后面2行来自于log方法,相差2秒左右。
前面2行在主线程中执行,后面2行在异步线程中执行。
5、获取异步返回值
用法
若需取异步执行结果,方法返回值必须为Future
类