• 为什么不能使用Executors.newFixedThreadPool和newCachedThreadPool


    newFixedThreadPool的阻塞队列大小是没有大小限制的,如果队列堆积数据太多会造成资源消耗。
    newCachedThreadPool是线程数量是没有大小限制的,当新的线程来了直接创建,同样会造成资源消耗殆尽。
    在新建线程池的时候使用ThreadPoolExecutor创建,阻塞队列可以使用ArrayBlockingQueue,这个队列的源码很金典,锁是一个成员变量。
    成员变量在堆内存中
    局部变量在栈内存保存
    比较好用的线程池;
    guava封装了很多实用的工具

    <dependency>
       <groupId>com.google.guava</groupId>
       <artifactId>guava</artifactId>
       <version>18.0</version>
    </dependency>

        1
        2
        3
        4
        5

    private final static int taskSize = 500;
    public static final ListeningExecutorService servicePool = MoreExecutors
          .listeningDecorator(new ThreadPoolExecutor(
              100, 100, 60000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(taskSize)));

        1
        2
        3
        4

    执行

    ListenableFuture<JSONObject> future = ServicePool.singService
                    .submit(() -> getdata(a,b,c));
    try {
         JSONObject jsonObject = future.get();
     } catch (InterruptedException e) {
          e.printStackTrace();
     } catch (ExecutionException e) {
          e.printStackTrace();
     }

        1
        2
        3
        4
        5
        6
        7
        8
        9

    想了解更多java相关技术,请关注公众号“JavaEE那些事”
    ---------------------
    作者:Awna
    来源:CSDN
    原文:https://blog.csdn.net/forwujinwei/article/details/79778344
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    ubuntu 16.04 网络配置之虚拟网卡的配置
    rabbitmq集群节点操作
    Ubuntu system zabbix-server-3.x install documentation
    PS RSS
    proxy_set_header设置Host为$proxy_host,$host与$local_host的区别
    centos 7 free 字段含义
    Linux atop 监控系统状态
    谨慎调整内核参数:vm.min_free_kbytes
    nginx反向代理http与https两种协议配置简述
    Python 获取以毫秒为单位的时间戳
  • 原文地址:https://www.cnblogs.com/tiancai/p/9951759.html
Copyright © 2020-2023  润新知