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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!