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.BasicThreadFactory ScheduledExecutorService 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 Pool ExecutorService 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="https://www.cnblogs.com/liran123/p/10" /> <property name="maxPoolSize" value="https://www.cnblogs.com/liran123/p/100" /> <property name="queueCapacity" value="https://www.cnblogs.com/liran123/p/2000" /> <property name="threadFactory" value= https://www.cnblogs.com/liran123/p/threadFactory />//in code userThreadPool.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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/141656.html
標籤:Java
