@Component
public class Calculation {
public Result cal(String req, int a, int b) {
System.out.println("请求id:" + req + " 结果:" + (a + b));
return new Result(req, a + b);
}
}
public class CallTask implements Callable<Result> {
private String req;
private int a;
private int b;
@Override
public Result call() throws Exception {
Calculation calculation = Main.applicationContext.getBean(Calculation.class);
return calculation.cal(req, a, b);
}
public CallTask(String req, int a, int b) {
this.req = req;
this.a = a;
this.b = b;
}
// getter and setter 等等
}
4.公共业务的线程类:
public class ElseTask implements Runnable {
private CompletionService<Result> cs;
private int threadCount;
public ElseTask(CompletionService<Result> cs, int threadCount) {
this.cs = cs;
this.threadCount = threadCount;
}
@Override
public void run() {
SomethingElse somethingElse = Main.applicationContext.getBean(SomethingElse.class);
doElse(somethingElse);
}
private void doElse(SomethingElse somethingElse) {
try {
for (int i = 0; i < threadCount; i++) {
Future<Result> take = cs.take();
Result result = take.get();
somethingElse.doElse(result);
}
} catch (Exception e) {
}
}
// getter and setter 等等
}
6.测试主方法:
@Service
public class Main implements ApplicationContextAware {
public static ApplicationContext applicationContext = null;
public static void main(String[] args) throws InterruptedException {
AbstractApplicationContext appContext = new ClassPathXmlApplicationContext("application01.xml");
ExecutorService executorService = Executors.newFixedThreadPool(100);
CompletionService<Result> cs = new ExecutorCompletionService(executorService);
//这里启动执行计算的线程
cs.submit(new CallTask("req001", 0, 1));
cs.submit(new CallTask("req002", 0, 2));
cs.submit(new CallTask("req003", 0, 3));
cs.submit(new CallTask("req004", 0, 4));
cs.submit(new CallTask("req005", 0, 5));
//专门的监控线程,并执行其他耗时的线程
executorService.execute(new ElseTask(cs, 5));
executorService.shutdown();
appContext.registerShutdownHook();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}