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