1. 程式人生 > >執行緒池Executors.newFixedThreadPool驗證以及總結

執行緒池Executors.newFixedThreadPool驗證以及總結

1、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個執行緒執行結束時間。