Java的線程池我想大家肯定不會陌生,在工作中或者自己平時的學(xué)習(xí)中多多少少都會用到,那你真的有了解過底層的實現(xiàn)原理嗎?還是說只停留在用的階段呢?而且關(guā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);?}
以上就是北大青鳥長沙麓谷校區(qū)java培訓(xùn)機構(gòu)的小編針對“如何應(yīng)對企業(yè)Java線程池面試題”的內(nèi)容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為你服務(wù)。
Java面試題