自定义线程数完成任务,据电脑配置(求质/素数)

关于大任务进行多线程处理,提高效率,自己的经验,有建议多多提问!全是干货,直接上代码

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();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值