国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

JAVA 創建線程池的注意事項

瀏覽:4日期:2022-08-29 08:11:35

1、創建線程或線程池時請指定有意義的線程名稱,方便出錯時回溯。創建線程池的時候請使用帶ThreadFactory的構造函數,并且提供自定義ThreadFactory實現或者使用第三方實現。

ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat('demo-pool-%d').build();ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));singleThreadPool.shutdown();public class TimerTaskThread extends Thread {public TimerTaskThread(){super.setName('TimerTaskThread'); …}

2、線程池不允許使用Executors去創建,而是通過ThreadPoolExecutor的方式,這樣的處理方式讓寫的同學更加明確線程池的運行規則,規避資源耗盡的風險。

說明:Executors返回的線程池對象的弊端如下:

1)FixedThreadPool和SingleThreadPool:  允許的請求隊列長度為Integer.MAX_VALUE,可能會堆積大量的請求,從而導致OOM。

2)CachedThreadPool:  允許的創建線程數量為Integer.MAX_VALUE,可能會創建大量的線程,從而導致OOM。

Positive example 1:

//org.apache.commons.lang3.concurrent.BasicThreadFactoryScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,new BasicThreadFactory.Builder().namingPattern('example-schedule-pool-%d').daemon(true).build());

Positive example 2:

ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat('demo-pool-%d').build();//Common Thread PoolExecutorService pool = new ThreadPoolExecutor(5, 200,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());pool.execute(()-> System.out.println(Thread.currentThread().getName()));pool.shutdown();//gracefully shutdown

Positive example 3:

<bean id='userThreadPool'class='org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor'><property name='corePoolSize' value='10' /><property name='maxPoolSize' value='100' /><property name='queueCapacity' value='2000' /><property name='threadFactory' value= threadFactory /><property name='rejectedExecutionHandler'><ref local='rejectedExecutionHandler' /></property></bean>//in codeuserThreadPool.execute(thread);

3、線程資源必須通過線程池提供,不允許在應用中自行顯式創建線程。

說明:

使用線程池的好處是減少在創建和銷毀線程上所花的時間以及系統資源的開銷,解決資源不足的問題。

如果不使用線程池,有可能造成系統創建大量同類線程而導致消耗完內存或者“過度切換”的問題。

ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat('demo-pool-%d').build();ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));singleThreadPool.shutdown();

以上就是JAVA 創建線程池的注意事項的詳細內容,更多關于JAVA 創建線程池注意事項的資料請關注好吧啦網其它相關文章!

標簽: Java
相關文章:
主站蜘蛛池模板: 皋兰县| 来安县| 永德县| 弋阳县| 宁阳县| 仁怀市| 达州市| 砀山县| 安岳县| 富源县| 思茅市| 满城县| 民勤县| 新田县| 环江| 海丰县| 合阳县| 德阳市| 莫力| 双柏县| 新晃| 涞水县| 湖南省| 同江市| 土默特左旗| 绥中县| 龙川县| 斗六市| 濉溪县| 和平县| 云阳县| 许昌市| 中牟县| 克什克腾旗| 麻江县| 乐东| 通化县| 文安县| 揭阳市| 贵定县| 贵德县|