3.使用線程池創建
from concurrent.futures import ThreadPoolExecutor
import time
"""
使用線程池創建
"""
# 學習某一個課程
def study(course):
for i in range(3):
time.sleep(1)
print("學習: " + course)
time.sleep(1)
print("---------------")
def main():
knowledge = ["Java", "Python", "Linux"]
# 最大線程數爲3,使用with可以自動關閉線程池,簡化操作
with ThreadPoolExecutor(3) as executor:
for each in knowledge:
executor.submit(study, each)
print("main線程over")
if __name__ == '__main__':
main()
"""
輸出結果:
學習: Java
學習: Python
學習: Linux
---------------
---------------
---------------
學習: Java
學習: Python
學習: Linux
------------------------------
---------------
學習: Java
學習: Python
學習: Linux
---------------
---------------
---------------
main線程over
"""