第 5-2 课:线程池——ThreadPoolExecutor + 面试题
生活随笔
收集整理的這篇文章主要介紹了
第 5-2 课:线程池——ThreadPoolExecutor + 面试题
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
線程池介紹
線程池(Thread Pool):把一個(gè)或多個(gè)線程通過統(tǒng)一的方式進(jìn)行調(diào)度和重復(fù)使用的技術(shù),避免了因?yàn)榫€程過多而帶來使用上的開銷。
為什么要使用線程池?
- 可重復(fù)使用已有線程,避免對(duì)象創(chuàng)建、消亡和過度切換的性能開銷。
- 避免創(chuàng)建大量同類線程所導(dǎo)致的資源過度競爭和內(nèi)存溢出的問題。
- 支持更多功能,比如延遲任務(wù)線程池(newScheduledThreadPool)和緩存線程池(newCachedThreadPool)等。
線程池使用
創(chuàng)建線程池有兩種方式:ThreadPoolExecutor 和 Executors,其中 Executors 又可以創(chuàng)建 6 種不同的線程池類型,會(huì)在下節(jié)講,本節(jié)重點(diǎn)來看看 ThreadPoolExecutor 的使用。
ThreadPoolExecutor 的使用
線程池使用代碼如下:
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue(100)); threadPoolExecutor.execute(new Runnable() {@Overridepublic void run() {// 執(zhí)行線程池System.out.println("Hello, Java.");} });以上程序執(zhí)行結(jié)果如下:
Hello, Java.
ThreadPoolExecutor 參數(shù)說明</
總結(jié)
以上是生活随笔為你收集整理的第 5-2 课:线程池——ThreadPoolExecutor + 面试题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 实战:Redis 性能测试
- 下一篇: 阿里为什么禁用Executors创建线程