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