join:等子线程执行完成,才执行主线程

setDaemon:主线程退出,子线程也会退出 (子线程为主线程的守护线程,不设置此参数主线程执行完成,子线程还会执行的)

可以看出子线程执行顺序不定,但是主线程是在所有子线程执行完毕之后才执行的

import threading
import time

start_time=time.time()
def test(p):
    time.sleep(0.001)
    print(p,threading.current_thread().name)


ts = []

for i in range(15):
    # target指定线程要执行的代码,args指定该代码的参数
    th = threading.Thread(target=test, args=[i])
    ts.append(th)
    ts.start()

for i in ts:

    i.join()

print("it is end !")
end_time=time.time()
print(end_time-start_time)

线程池

import threading
import time
from concurrent.futures import ThreadPoolExecutor
start_time=time.time()
def test(p):
    time.sleep(0.001)
    print(p,threading.current_thread().name)


with ThreadPoolExecutor(max_workers=15) as pool:
    for i in range(16):
        pool.submit(test,(i))

print("it is end !")
end_time=time.time()
print(end_time-start_time)