概述
以下为测试类
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.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {
@Autowired
private TestAsync testAsync;
/**
* 测试带返回值的异步多线程
*/
@Test
public void testAsync(){
try{
long start = System.currentTimeMillis();
List<Future<Integer>> futures = new ArrayList<>();
for(int i=0; i<10; i++){
Future<Integer> future = testAsync.testAsyncReturn();
futures.add(future);
}
Integer finalCount = 0;
for (Future future : futures) {
Integer count = (Integer) future.get();
finalCount += count;
}
long end = System.currentTimeMillis();
System.out.println(String.format("finalCount = %s, 耗时:%s", finalCount, (end-start)));
}catch (Exception e){
e.printStackTrace();
}
}
}
以下为异步线程类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
@Component
public class TestAsync {
@Configuration
@EnableAsync
public class ExecutorInitUser{
@Bean
public Executor testExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(50);
executor.setMaxPoolSize(1000);
executor.setQueueCapacity(10000);
executor.setThreadNamePrefix("test-executor");
return executor;
}
}
@Async("testExecutor")
public Future<Integer> testAsyncReturn(){
try {
// 实现业务逻辑
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new AsyncResult<Integer>(1000);
}
}
最后
以上就是陶醉月饼为你收集整理的springboot注解模式带返回值的异步多线程实现的全部内容,希望文章能够帮你解决springboot注解模式带返回值的异步多线程实现所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复