多线程之java中线程池的使用

 

一、使用线程池的原因

             1、可以减少平凡的创建的线程,耗费cpu资源

             2、创建的线程不用去手动的关闭

             3、控制线程的数量

             4、响应的速度更快

二、线程池的5种类型

            1、固定数量的     

                        

                 Executors.newFixedThreadPool(1);

            2、单例

            

                 Executors.newSingleThreadExecutor();

            3、缓存

                

                 Executors.newCachedThreadPool();

            4、定时

                 Executors.newScheduledThreadPool(1);

            5、foke/join框架创建线程池

 

三、线程池的常见用

            1、使用Submit方式进行提交

package com.gpdi.security;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceDemo2 implements Runnable{
    @Override
    public void run() {
        System.out.println("执行当前线程的是"+Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        ExecutorService executorService= Executors.newFixedThreadPool(10);
        for(int  i=0;i<100;i++){
            executorService.execute(new ExecutorServiceDemo2());
        }
        executorService.shutdown();
    }
}

         

         2、ExecutorService 和Callable进行组合使用实现带返回值的多线程(这里用一个我们常见的应用场景),运用多线程进行查询数据库然后将结果进行合并,现在我们将40万数据分为5个线程进行查询,最终合并结果)

 

package com.gpdi.controller;

import com.fasterxml.jackson.core.JsonParser;
import com.gpdi.service.BusinessService;
import com.gpdi.entity.Business;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author : whs
 * @description:交易订单控制器
 * @date 2019
 */

@RestController
public class BusinessController {
    /**
     * */
    @RequestMapping(value = "getBusiness")
    public long getBusiness() {

        long beginTime = System.currentTimeMillis();
        String sql = "select * from business limit 400000";//6s
        List<Business> list = businessService.getBussinesListBySql(sql);
        //  System.out.println(list.get(0).getId());
        // System.out.println(list.get(399999).getId());
        long endTime = System.currentTimeMillis();
        return endTime - beginTime;


    }

    /**
     * */
    @RequestMapping(value = "getBusinessByThread")
    public long getBusinessByThread() throws Exception {


        int num = 400000;
        int everyPart = 80000;
        int allPart = 0;
        if (num % everyPart == 0) {
            allPart = num / everyPart;
        } else {
            allPart = num / everyPart + 1;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < allPart; i++) {

            int key = i * everyPart + 1;
            int value = (i + 1) * everyPart;
            map.put(key, value);
        }


        long beginTime = System.currentTimeMillis();
        /**
         * @description:实现的思路
         *
         *   将40万数据分为5个线程
         */

        //创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(10);

        List<Future> list = new ArrayList<>();
        int count = 1;

        for (Integer key : map.keySet()) {
               
            
            Callable callable = new MyCallable(count, key, map.get(key));
            Future future = pool.submit(callable);
            list.add(future);
            count += 1;
        }

        List<Business> allBusinessList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Object object = list.get(i).get();
            List<Business> list1 = (List<Business>) object;
            allBusinessList.addAll(list1);
        }

        System.out.println("拿到的是什么的数量" + allBusinessList.size());


        long endTime = System.currentTimeMillis();
        return endTime - beginTime;


    }


    /**
         创建一个Callable工具类
    */
    class MyCallable implements Callable<Object> {
        private int taskId;
        private int beginId;
        private int endId;

        public int getBeginId() {
            return beginId;
        }

        public void setBeginId(int beginId) {
            this.beginId = beginId;
        }

        public int getEndId() {
            return endId;
        }

        public void setEndId(int endId) {
            this.endId = endId;
        }

        public MyCallable(int beginId, int endId) {
            this.beginId = beginId;
            this.endId = endId;
        }

        public int getTaskId() {
            return taskId;
        }

        public void setTaskId(int taskId) {
            this.taskId = taskId;
        }

        public MyCallable(int taskId, int beginId, int endId) {
            this.taskId = taskId;
            this.beginId = beginId;
            this.endId = endId;
        }

        @Override
        public Object call() throws Exception {
            System.out.println(">>>" + taskId + "号线程任务启动");
            String mysql = "select * from business where id>=" + beginId + "  and id<=" + endId;
            System.out.println("这个sql语句是" + mysql);
            List<Business> list = businessService.getBussinesListBySql(mysql);
            System.out.println(">>>" + taskId + "号线程任务完毕");
            return list;
        }
    }

    @Autowired
    BusinessService businessService;
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值