更新時間:2020-06-19 13:18:29 來源:動力節(jié)點 瀏覽2585次
Java的線程池我想大家肯定不會陌生,在工作中或者自己平時的學習中多多少少都會用到,那你真的有了解過底層的實現(xiàn)原理嗎?還是說只停留在用的階段呢?而且關于Java線程池也是在面試中的一個高頻的面試題,就像HashMap的實現(xiàn)原理一樣,基本上面試必問,估計都已經(jīng)被問爛大街了。
常用的幾種線程池
我們先來看下常用的幾種線程池的創(chuàng)建方式,以及底層采用的實現(xiàn)原理
單個線程:
Executors.newSingleThreadExecutor();
public?static?ExecutorService?newSingleThreadExecutor()?{
?return?new?FinalizableDelegatedExecutorService
?(new?ThreadPoolExecutor(1,?1,
?0L,?TimeUnit.MILLISECONDS,
?new?LinkedBlockingQueue<Runnable>()));
?}
緩存線程:
Executors.newCachedThreadPool();
public?static?ExecutorService?newCachedThreadPool()?{
?return?new?ThreadPoolExecutor(0,?Integer.MAX_VALUE,
?60L,?TimeUnit.SECONDS,
?new?SynchronousQueue<Runnable>());
?}
固定線程:
Executors.newFixedThreadPool(2);
public?static?ExecutorService?newFixedThreadPool(int?nThreads)?{
?return?new?ThreadPoolExecutor(nThreads,?nThreads,
?0L,?TimeUnit.MILLISECONDS,
?new?LinkedBlockingQueue<Runnable>());
?}
定時線程:
Executors.newScheduledThreadPool(3);(父類中)
public?ThreadPoolExecutor(int?corePoolSize,
?int?maximumPoolSize,
?long?keepAliveTime,
?TimeUnit?unit,
?BlockingQueue<Runnable>?workQueue)?{
?this(corePoolSize,?maximumPoolSize,?keepAliveTime,?unit,?workQueue,
?Executors.defaultThreadFactory(),?defaultHandler);
?}
以上就是動力節(jié)點java培訓機構的小編針對“如何應對企業(yè)Java線程池面試題”的內(nèi)容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為你服務。