先看一下同步执行时的效果
@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());
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.cnblogs.com/onlyrun/p/16445903.html
内容来源于网络,如有侵权,请联系作者删除!