自定义线程池,解决线程占满没有响应的问题
1、 首先进行创建配置类,通知bean容器进行创建线程池,对线程进行管理
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Bean(name = "zpPool")
public ThreadPoolExecutor zpPool() {
return new ThreadPoolExecutor(
//核心线程数
5,
//最大线程数
5,
60,
TimeUnit.SECONDS,
//队列大小
new LinkedBlockingDeque<Runnable>(Integer.MAX_VALUE),
//定义线程名称
new ThreadFactory() {
private final AtomicInteger mThreadNum = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "zpPool-" + mThreadNum.getAndIncrement());
}
},
//拒绝策略
new ThreadPoolExecutor.AbortPolicy()
);
}
}
2、 编写controller 进行线程池的测试工作
@RestController
@Api(tags = "线程池中多线程的测试")
public class manyXcTest {
@Resource
testAsync testAscy;
@PostMapping("/testAscy")
@ApiOperation("自定义线程池的测试")
@AuthPassport
public Result testAsync() {
testAscy.testAscy();
return new Result();
}
}
3、 service中进行调用异步方法一定是加入bean容器中的,synchronized锁保证数据可靠性
@Service
public class testAsync {
@SneakyThrows
@Async("zpPool")
public void testAscy() {
int i = 0;i++;
int j=0;
System.out.println("多线程线程池任务测试 " + i);
for ( j = 0; j < 10; j++) {
System.out.println("多线程线程池任务测试 " + j+"开始");
}
System.out.println("多线程线程池任务测试 " + j+"结束");
synchronized(this){
Thread.sleep(60000);
System.out.println("多线程线程池任务测试 " + j+"结束");
}
}
}
## 在分布式部署的情况下还有一种方式能够进行保证线程使用的稳定性
```java
@XxlJob(value = "zpJob", init = "init", destroy = "destroy")
public void zpJob1() {
XxlJobHelper.log("zpJob开始执行");
XxlJobHelper.log("zpJob结束执行");
}
}