首先呢,我设计了一个图表在我的项目里面,为了方便展示,我只修改一个字段,线程池设置参数 (2,4,30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(4),new RJ());
然后通过循环持续的进行增加任务,目的修改数据库的gentoal字段
拒绝策略:
public class RJ implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
RunT runT = (RunT) r;
Chart chart = runT.getChart();
chart.setGoal("拒绝");
runT.getChartService().save(chart);
}
}
任务:
package com.xxbi.springbootinit.Reject;
import com.xxbi.springbootinit.model.entity.Chart;
import com.xxbi.springbootinit.service.ChartService;
public class RunT implements Runnable{
private final Chart chart;
private final String goal;
private final ChartService chartService;
public Chart getChart() {
return chart;
}
public String getGoal() {
return goal;
}
public ChartService getChartService() {
return chartService;
}
@Override
public void run() {
try {
chart.setGoal(goal);
chartService.save(chart);
} catch (Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public RunT(Chart chart,String goal,ChartService chartService){
this.chart=chart;
this.chartService=chartService;
this.goal=goal;
}
}
测试:
@SpringBootTest
public class M {
@Resource
private ChartService chartService;
@Test
public void h() throws InterruptedException {
ThreadPoolExecutor t=new ThreadPoolExecutor(2,4,30,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(4),new RJ());
for(int i=0;i<10;i++){
Chart chart =new Chart();
String goal="goal"+i;
System.out.println(goal);
RunT runT=new RunT(chart,goal,chartService);
t.execute(runT);
}
// 关闭线程池
t.shutdown();
// 等待所有任务完成
if (!t.awaitTermination(1, TimeUnit.MINUTES)) {
System.out.println("未终止");
t.shutdownNow();
}
}
}