为什么不能使用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
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/tiancai/p/9951759.html