关于大任务进行多线程处理,提高效率,自己的经验,有建议多多提问!全是干货,直接上代码
1.线程容器
public class ThreadPoolUtil {
ConcurrentLinkedQueue<Integer> workerQueue = new ConcurrentLinkedQueue();
List<Thread> list = new ArrayList<Thread>();
public ThreadPoolUtil(Work work, int workCounts){
work.setWorkerQueue(this.workerQueue);
for (int i = 0; i < workCounts; i++) {
list.add(new Thread(work));
}
}
public void submit(Integer num) {
workerQueue.add(num);
}
public void execute() {
for (Thread thread : list) {
thread.start();
}
}
public boolean isComplete() {
for (Thread thread : list) {
if(thread.getState() != Thread.State.TERMINATED){
return false;
}
}
return true;
}
}
2.任务处理逻辑并填入容器
public class Work implements Runnable {
ConcurrentLinkedQueue<Integer> wq = new ConcurrentLinkedQueue();
@Override
public void run() {
while(true){
Integer num = wq.poll();
if(num==null){
break;
}else{
boolean flag = true;
for(int b=2;b<num;b++){
if(num%b==0){
flag=false;
break;
}
}
if(flag){
System.out.println("质数为:"+num);
}
}
}
}
public void setWorkerQueue(ConcurrentLinkedQueue<Integer> wq) {
this.wq = wq;
}
}
3.处理请求
@GetMapping(value = "/queryNum")
public ResponseJson queryNum(@RequestParam(value = "num", required = false) int num) throws MeidianException {
//根据电脑配置-最大开通线程数
int p = Runtime.getRuntime().availableProcessors() * 2;
ThreadPoolUtil threadPoolUtil = new ThreadPoolUtil(new Work(), p);
for(int i=1;i<=num;i++){
threadPoolUtil.submit(i);
}
threadPoolUtil.execute();
while (true) {
if (threadPoolUtil.isComplete()) {
break;
}
}
return ResponseJson.getSuccessResponse();
}