阻塞队列结合线程池使用

1.运行方法
public  void test() throws Exception {
        //定义阻塞队列长度
        ArrayBlockingQueue<String> blockingDeque = new ArrayBlockingQueue<String>(20);
        //定义生产者
        Producer producer = new Producer(blockingDeque);
        //定义消费者
        Consumer consumer = new Consumer(blockingDeque);
        //定义阻塞队列,5为线程数为5
        ExecutorService service = Executors.newScheduledThreadPool(5);
		//生产者生产
        service.execute(producer);
        //消费者消费生产者
        //注意,此处写了10个消费者,但是由于线程池数量为5,所以消费者开启的线程实际上是4个
        for (int i = 0; i <10 ; i++) {
            System.out.println("消费者"+i);
          service.execute(consumer);
        }
    }
2.生产者


import lombok.SneakyThrows;

import java.util.concurrent.ArrayBlockingQueue;

/**

 * @Description:
 * @Author:ay
 * @Date:2020/10/14
 */
public class Producer implements Runnable {
    private ArrayBlockingQueue<String> arrayBlockingQueue;

    public Producer(ArrayBlockingQueue<String> arrayBlockingQueue) {
        this.arrayBlockingQueue = arrayBlockingQueue;
    }

    @Override
    public void run() {
        System.out.println("生产者"+Thread.currentThread().getName());

        int i = 100;
        System.out.println("我是生产者"+i);
        while (i<999){
            try {

                arrayBlockingQueue.put("生产者"+i++);
                System.out.println("放进去的元素是:  生产者"+i);
            } catch (InterruptedException e) {
                System.out.println("生产者停止生产");
                e.printStackTrace();
            }
        }

    }
}

3.消费者

import com.alibaba.fastjson.JSONObject;
import com.geostar.zrzy.zwfw.dao.BdcYbdyhDao;
import com.geostar.zrzy.zwfw.entity.BdcYbdyh;
import com.geostar.zrzy.zwfw.service.BdcYbdyhService;
import com.geostar.zrzy.zwfw.utils.HttpClientUtils;
import lombok.Data;
import org.apache.avalon.framework.context.Context;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jca.context.SpringContextResourceAdapter;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @Description:
 * @Author:ay
 * @Date:2020/10/14
 */
@Data

public class Consumer implements Runnable {
      BdcYbdyhDao bdcYbdyhDao =  AppBean.getBean(BdcYbdyhDao.class);
       BdcYbdyhService bdcYbdyhService =AppBean.getBean(BdcYbdyhService.class);

    private ArrayBlockingQueue<String> arrayBlockingQueue;

    public Consumer(ArrayBlockingQueue<String> arrayBlockingQueue) {
        this.arrayBlockingQueue = arrayBlockingQueue;
    }

    @Override
    public void run() {
        System.out.println("消费者"+Thread.currentThread().getName());

        while (true){
            try {

                String take = arrayBlockingQueue.take();
                System.out.println(take);
                /
                System.out.println("我现在进入了方法");
                String dbcode = "18";
                List<Map<String, String>> list = new ArrayList<>();
                List<Map<String, String>> danrenlist = new ArrayList<>();
                List<Map<String, String>> duoRenlist = new ArrayList<>();
                Map<String,List> hashMap = new HashMap<>();
  
                System.out.println("hahha"+take);
                Map<String, String> map = new HashMap<>();
        
                Map<String, Object> reqMap = new HashMap<>();
                reqMap.put("DBCode", dbcode);
                reqMap.put("iCode", take);
                String result = HttpClientUtils.executePostString("url****", reqMap, "utf-8", 30 * 1000);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String fwyt  = bdcYbdyhDao.getFwyt(take);
                List<String> fwytlist = new ArrayList();
                fwytlist.add("住宅");
                fwytlist.add("商业服务");
                fwytlist.add("成套别墅");
                fwytlist.add("别墅");
                fwytlist.add("高档公寓");
                fwytlist.add("非成套住宅");
                fwytlist.add("集体宿舍");
                fwytlist.add("商业、金融、信息");
                fwytlist.add("商业服务");
                fwytlist.add("经营");
                fwytlist.add("旅游");
                fwytlist.add("金融保险");
                fwytlist.add("电讯信息");
                if (jsonObject != null) {
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject data = JSONObject.parseObject(result).getJSONObject("data");
                        if (data != null) {
                            int len = 0;
                            if (data.get("APPLYMAN2").toString().contains(",")) {
                                len = data.get("APPLYMAN2").toString().split(",").length;
                            } else if (data.get("APPLYMAN2").toString().contains(" ")) {
                                len = data.get("APPLYMAN2").toString().split(" ").length;
                            }

                            //      System.out.println(len);
                            if(len ==0){
                                if (fwytlist.contains(fwyt)){
                                    map.put("fwyt", fwyt);
                                    map.put("bdcdyh", bdcYbdyhService.getBdcdyh(take));
                                    danrenlist.add(map);
                                    hashMap.put("房子",danrenlist);
                                }
                            }
                        }
                    }
                }
                if(!hashMap.isEmpty()){
                    File file = new File("D:/testthead.txt");

                    OutputStream outputStream = new FileOutputStream(file,true);
                    outputStream.write(JSONObject.toJSONString(hashMap).getBytes("UTF-8"));
                    outputStream.close();
                }

            } catch (InterruptedException e) {
                System.out.println("消费者在等待");
                e.printStackTrace();
            } catch (Exception e) {
                System.out.println("解析错误!");
                e.printStackTrace();
            }
        }
    }
}

代码不全,有些隐私事项不方便展示,大家参考原理使用
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot中,可以使用线程池和CompletableFuture一起工作来提高应用程序的并发性能和响应性。 首先,你可以使用`ThreadPoolTaskExecutor`类来创建一个线程池。在Spring Boot中,你可以通过在应用程序的配置文件中添加以下属性来配置线程池: ```properties # 线程池配置 spring.task.execution.pool.core-size=10 spring.task.execution.pool.max-size=20 spring.task.execution.pool.queue-capacity=1000 spring.task.execution.pool.thread-name-prefix=my-thread- ``` 这个配置将创建一个具有10个核心线程和20个最大线程的线程池,以及一个容量为1000的工作队列。你可以根据你的需求进行调整。 接下来,你可以使用CompletableFuture来异步执行任务。CompletableFuture是一个Java 8引入的类,可以用于进行异步编程。你可以使用它的`supplyAsync()`方法来异步执行一个任务,并返回一个Future对象。 ```java CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { // 执行异步任务 return "任务结果"; }); ``` 你可以在CompletableFuture对象上调用`thenApply()`、`thenAccept()`或`thenRun()`等方法来处理异步任务的结果或执行其他操作。这些方法接收一个函数作为参数,用于处理任务的结果。 ```java future.thenApply(result -> { // 处理任务结果 return "处理后的结果"; }); ``` 在处理任务结果时,你可以利用线程池来执行一些耗时的操作,以避免阻塞线程。你可以通过在CompletableFuture对象上调用`thenApplyAsync()`、`thenAcceptAsync()`或`thenRunAsync()`方法来异步执行操作。 ```java future.thenApplyAsync(result -> { // 异步处理任务结果 return "处理后的结果"; }, executor); ``` 在这里,`executor`是你之前配置的线程池对象。 通过将线程池和CompletableFuture结合起来使用,你可以实现更高效的并发处理和响应性能。记得根据实际需求调整线程池的配置,以避免资源浪费或线程饥饿等问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值