線程池Executors.newFixedThreadPool驗證以及總結


Executors在於java.util.comcurrent.包下,Executors.newFixedThreadPool(n)創建容器大小為n的線程池,表示正在執行中的線程只有n個

public class TestExecute {
 
    public static void main(String[] args) {
        Executor exe = Executors.newFixedThreadPool(2);
 
        for (int i = 0; i < 3; i++) {
            ExeThreads ex = new ExeThreads();
            exe.execute(ex);
 
        }
 
    }
 
}
 
class ExeThreads implements Runnable {
 
    @Override
    public void run() {
        try {
            System.out.println("run start-----------------" + System.currentTimeMillis());
            Thread.sleep(15 * 1000);
            System.out.println("run end-----------------" + System.currentTimeMillis());
 
        }
        catch (InterruptedException e) {
 
            e.printStackTrace();
        }
 
    }
 
}

實驗結果如下:

事例總結:線程池大小為2,但是要執行的線程是3個。所以正在執行的線程只有2個,正在執行的2個線程的開始時間為1536907573338,2個線程的結束時間為1536907588338,第3個線程的開始時間,剛剛好是前面2個線程執行結束時間。

————————————————
版權聲明:本文為CSDN博主「lindata」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_42394615/article/details/82702928


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM