使用@Async注解异步执行

同步执行

先看一下同步执行时的效果

代码示例

@Component
public class CommonExecutor {
public void doTaskOne() {
doTask("One");
}
public void doTaskTwo() {
doTask("Two");
}
public void doTaskThree() {
doTask("Three");
}
private void doTask(String name) {
System.out.println("执行任务-" + name + " thread:" + Thread.currentThread().getName());
StopWatch stopwatch = new StopWatch("任务" + name);
stopwatch.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
stopwatch.stop();
System.out.println("任务-" + name + " 耗时(ms):" + stopwatch.getTotalTimeMillis());
}
}

测试类

@SpringBootTest
public class CommonTest {
@Autowired
private CommonExecutor commonExecutor;
@Test
public void testExecutor(){
StopWatch stopwatch = new StopWatch("同步执行");
stopwatch.start();
commonExecutor.doTaskOne();
commonExecutor.doTaskTwo();
commonExecutor.doTaskThree();
stopwatch.stop();
System.out.println("同步执行 总耗时(ms):" + stopwatch.getTotalTimeMillis());
}
}

测试结果

异步执行

再来看一下使用异步优化后的执行效果

代码示例

@Component
public class CommonExecutorAsync {
// 用指定的线程池
@Async("testExecutor")
public CompletableFuture<String> doTaskOne() {
return doTask("One");
}
@Async("testExecutor")
public CompletableFuture<String> doTaskTwo() {
return doTask("Two");
}
@Async("testExecutor")
public CompletableFuture<String> doTaskThree() {
return doTask("Three");
}
private CompletableFuture<String> doTask(String name) {
System.out.println("执行任务-" + name + " thread:" + Thread.currentThread().getName());
StopWatch stopwatch = new StopWatch("任务" + name);
stopwatch.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
stopwatch.stop();
System.out.println("任务-" + name + " 耗时(ms):" + stopwatch.getTotalTimeMillis());
return CompletableFuture.completedFuture("任务" + name + "完成");
}
}

定义线程池

@Configuration
public class ExecutorThreadPool {
@Bean("testExecutor")
public ExecutorService executorService() {
return new ThreadPoolExecutor(1, 5, 5, TimeUnit.SECONDS,
new SynchronousQueue<>(), new ThreadFactoryBuilder().setNameFormat("testExecutor-%d").build());
}
}

测试类

@EnableAsync //允许开启异步的注解
@SpringBootTest
public class CommonTest {
@Autowired
private CommonExecutorAsync commonExecutorAsync;
@Test
public void testExecutorAsync(){
StopWatch stopwatch = new StopWatch("异步执行");
stopwatch.start();
CompletableFuture<String> aFuture = commonExecutorAsync.doTaskOne();
CompletableFuture<String> bFuture = commonExecutorAsync.doTaskTwo();
CompletableFuture<String> cFuture = commonExecutorAsync.doTaskThree();
CompletableFuture.allOf(aFuture,bFuture,cFuture).join();
stopwatch.stop();
System.out.println("异步执行 总耗时(ms):" + stopwatch.getTotalTimeMillis());
}
}

测试结果

posted @   我自逍遥  阅读(184)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示