一、線程池簡(jiǎn)易版
思路先創(chuàng)建一個(gè)隊(duì)列吠勘,因?yàn)殛?duì)列先進(jìn)先出妆艘,使用后就消失了彤灶,隊(duì)列里面儲(chǔ)存最大線程數(shù),方法一個(gè)是調(diào)取線程批旺,一個(gè)是儲(chǔ)存線程
import queue
import threading
import time
class ThreadPool(object):
#初始化類幌陕,所以創(chuàng)建線程初始化線程
def __init__(self,maxsize):
self.queue = queue.Queue()
for i in range(maxsize):
self.queue.put(threading.Thread)
#使用隊(duì)列中 的get方法
def get_thread(self):
return self.queue.get()
#使用隊(duì)列中put方法
def add_thread(self):
self.queue.put(threading.Thread)
#實(shí)驗(yàn)的方法
def f(i,ret):
time.sleep(0.2)
print(i,threading.current_thread())
#每次啟動(dòng)線程就往對(duì)了列中加等同的線程(最后剩余數(shù)等于最大線程數(shù))
ret.add_thread()
#創(chuàng)建線程池對(duì)象
ret = ThreadPool(5)
for i in range(10):
#取出線程池中的線程(threading.Thread)相等于t =threading.Thread
p = ret.get_thread()
#調(diào)用線程池對(duì)象,加線程
t=p(target = f,args = (i,ret,))
t.start()
time.sleep(0.5)
print(ret.queue.qsize())
》》
3 <Thread(Thread-4, started 6264)>
4 <Thread(Thread-5, started 332)>
1 <Thread(Thread-2, started 7396)>
0 <Thread(Thread-1, started 2472)>
2 <Thread(Thread-3, started 8592)>
9 <Thread(Thread-10, started 6584)>
7 <Thread(Thread-8, started 5952)>
8 <Thread(Thread-9, started 1844)>
6 <Thread(Thread-7, started 8940)>
5 <Thread(Thread-6, started 2476)>
5
根據(jù)上面的代碼發(fā)現(xiàn)汽煮,最后隊(duì)列中的數(shù)量等于最大線程數(shù)也就是當(dāng)線程都結(jié)束了搏熄,隊(duì)列中實(shí)際還是保留著五個(gè)線程