创建线程需要向系统申请资源,线程切换时操作系统会切换线程上下文,可能会从用户态切换到内核态,当有很多线程时,频繁地切换线程会导致消耗大量的 CPU 以及内核资源,真正用于计算的资源就减少了,反而会降低程序的效率。线程并不是越多越好,线程池的作用是管理、复用、回收一组线程,控制线程的数量,避免频繁的创建和销毁线程而浪费资源。
Start thread 1 at 27:05.541 Start thread 6 at 27:05.541 Start thread 5 at 27:05.541 Start thread 2 at 27:05.541 Start thread 3 at 27:05.541 Start thread 8 at 27:05.541 Start thread 7 at 27:05.541 Start thread 4 at 27:05.541 End thread 6 at 27:06.854 ~Task() with ID 6 End thread 1 at 27:06.854 ~Task() with ID 1 End thread 8 at 27:06.854 ~Task() with ID 8 End thread 3 at 27:06.854 ~Task() with ID 3 End thread 7 at 27:06.854 End thread 4 at 27:06.854 End thread 2 at 27:06.854 ~Task() with ID 7 End thread 5 at 27:06.854 ~Task() with ID 4 ~Task() with ID 2 ~Task() with ID 5 Start thread 9 at 27:06.855 Start thread 10 at 27:06.855 Start thread 11 at 27:06.855 Start thread 12 at 27:06.855 Start thread 13 at 27:06.855