1.常規(guī)代碼順序執(zhí)行
如下定義三個(gè)任務(wù),然后在單元測(cè)試依次調(diào)用三個(gè)任務(wù)原叮,可以看到執(zhí)行結(jié)果是先后執(zhí)行三個(gè)任務(wù)温赔,必須等待前一個(gè)任務(wù)結(jié)束后才能開(kāi)始下一個(gè)任務(wù),總共耗時(shí)6000多毫秒
測(cè)試類
package com.ghw.async;
import javafx.scene.paint.Stop;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StopWatch;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncApplicationTests {
@Autowired
private Task task;
private static StopWatch stopWatch = new StopWatch();
@Test
public void contextLoads() {
}
@Test
public void test() throws Exception {
task.setStopWatch(stopWatch);
task.doTaskOne();
task.doTaskTwo();
task.doTaskThree();
System.out.println(stopWatch.prettyPrint());
}
}
Task類
package com.ghw.async;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Component
public class Task {
private StopWatch stopWatch;
public void setStopWatch(StopWatch stopWatch) {
this.stopWatch = stopWatch;
}
public void doTaskOne() throws Exception {
stopWatch.start("task1");
TimeUnit.SECONDS.sleep(2);
stopWatch.stop();
}
public void doTaskTwo() throws Exception {
stopWatch.start("task2");
TimeUnit.SECONDS.sleep(2);
stopWatch.stop();
}
public void doTaskThree() throws Exception {
stopWatch.start("task3");
TimeUnit.SECONDS.sleep(2);
stopWatch.stop();
}
}
執(zhí)行結(jié)果
StopWatch '': running time (millis) = 6039
-----------------------------------------
ms % Task name
-----------------------------------------
02014 033% task1
02013 033% task2
02012 033% task3
2.采用@Async注解異步執(zhí)行
Task類
package com.ghw.async;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@Component
public class Task {
@Async
public Future<String> doTaskOne() throws Exception {
StopWatch stopWatch = new StopWatch();
String task = "task1";
stopWatch.start(task);
TimeUnit.SECONDS.sleep(2);
stopWatch.stop();
System.out.println(task + " spend time:" + stopWatch.getLastTaskTimeMillis());
return new AsyncResult<>(task + " is finished");
}
@Async
public Future<String> doTaskTwo() throws Exception {
StopWatch stopWatch = new StopWatch();
String task = "task2";
stopWatch.start(task);
TimeUnit.SECONDS.sleep(2);
stopWatch.stop();
System.out.println(task + " spend time:" + stopWatch.getLastTaskTimeMillis());
return new AsyncResult<>(task + " is finished");
}
@Async
public Future<String> doTaskThree() throws Exception {
StopWatch stopWatch = new StopWatch();
String task = "task3";
stopWatch.start(task);
TimeUnit.SECONDS.sleep(2);
stopWatch.stop();
System.out.println(task + " spend time:" + stopWatch.getLastTaskTimeMillis());
return new AsyncResult<>(task + " is finished");
}
}
測(cè)試類
package com.ghw.async;
import javafx.scene.paint.Stop;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StopWatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncApplicationTests {
@Autowired
private Task task;
private static StopWatch stopWatch = new StopWatch();
@Test
public void contextLoads() {
}
@Test
public void test() throws Exception {
StopWatch stopWatch = new StopWatch();
stopWatch.start("all");
Future<String> task1 = task.doTaskOne();
Future<String> task2 = task.doTaskTwo();
Future<String> task3 = task.doTaskThree();
while (true) {
if (task1.isDone() && task2.isDone() && task3.isDone()) {
// 三個(gè)任務(wù)都調(diào)用完成它褪,退出循環(huán)等待
break;
}
}
stopWatch.stop();
System.out.println("all task spend time:" + stopWatch.getLastTaskTimeMillis());
}
}
執(zhí)行結(jié)果
task3 spend time:2014
task1 spend time:2014
task2 spend time:2014
all task spend time:2060
可以看出只需要2060毫秒饵骨,三個(gè)任務(wù)就全部執(zhí)行完成了,相比第一種方法茫打,能夠提高3倍速度居触。
其中使用Future<T>
來(lái)返回異步調(diào)用的結(jié)果。在while循環(huán)中判斷包吝,當(dāng)三個(gè)任務(wù)全部完成的時(shí)候,退出while循環(huán)源葫。
采用自己配置的線程池
package com.ghw.async;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class Task {
@Async(value = "taskExecutor")
public void doTaskOne() throws Exception {
log.info("開(kāi)始做任務(wù)一");
StopWatch stopWatch = new StopWatch();
String task = "task1";
stopWatch.start(task);
TimeUnit.SECONDS.sleep(2);
stopWatch.stop();
log.info("完成任務(wù)一诗越,耗時(shí):" + (stopWatch.getLastTaskTimeMillis()) + "毫秒");
}
@Async(value = "taskExecutor")
public void doTaskTwo() throws Exception {
log.info("開(kāi)始做任務(wù)二");
StopWatch stopWatch = new StopWatch();
String task = "task2";
stopWatch.start(task);
TimeUnit.SECONDS.sleep(2);
stopWatch.stop();
log.info("完成任務(wù)二,耗時(shí):" + (stopWatch.getLastTaskTimeMillis()) + "毫秒");
}
@Async(value = "taskExecutor")
public void doTaskThree() throws Exception {
log.info("開(kāi)始做任務(wù)三");
StopWatch stopWatch = new StopWatch();
String task = "task3";
stopWatch.start(task);
TimeUnit.SECONDS.sleep(2);
stopWatch.stop();
log.info("完成任務(wù)三息堂,耗時(shí):" + (stopWatch.getLastTaskTimeMillis()) + "毫秒");
}
}
package com.ghw.async;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@SpringBootApplication
public class AsyncApplication {
public static void main(String[] args) {
SpringApplication.run(AsyncApplication.class, args);
}
@EnableAsync
@Configuration
class TaskPoolConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
}
單元測(cè)試
package com.ghw.async;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StopWatch;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncApplicationTests {
@Autowired
private Task task;
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
private static StopWatch stopWatch = new StopWatch();
@Test
public void contextLoads() {
}
@Test
public void test() throws Exception {
task.doTaskOne();
task.doTaskTwo();
task.doTaskThree();
Thread.currentThread().join();
}
}