JAVA 創(chuàng)建線程池的注意事項
1、創(chuàng)建線程或線程池時請指定有意義的線程名稱,方便出錯時回溯。創(chuàng)建線程池的時候請使用帶ThreadFactory的構(gòu)造函數(shù),并且提供自定義ThreadFactory實現(xiàn)或者使用第三方實現(xiàn)。
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去創(chuàng)建,而是通過ThreadPoolExecutor的方式,這樣的處理方式讓寫的同學(xué)更加明確線程池的運行規(guī)則,規(guī)避資源耗盡的風(fēng)險。
說明:Executors返回的線程池對象的弊端如下:
1)FixedThreadPool和SingleThreadPool: 允許的請求隊列長度為Integer.MAX_VALUE,可能會堆積大量的請求,從而導(dǎo)致OOM。
2)CachedThreadPool: 允許的創(chuàng)建線程數(shù)量為Integer.MAX_VALUE,可能會創(chuàng)建大量的線程,從而導(dǎo)致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、線程資源必須通過線程池提供,不允許在應(yīng)用中自行顯式創(chuàng)建線程。
說明:
使用線程池的好處是減少在創(chuàng)建和銷毀線程上所花的時間以及系統(tǒng)資源的開銷,解決資源不足的問題。
如果不使用線程池,有可能造成系統(tǒng)創(chuàng)建大量同類線程而導(dǎo)致消耗完內(nèi)存或者“過度切換”的問題。
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 創(chuàng)建線程池的注意事項的詳細(xì)內(nèi)容,更多關(guān)于JAVA 創(chuàng)建線程池注意事項的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
