#!/usr/local/bin/python3
import queue
import threading
import time
false = 0
def run_data(run_name, quit):
while not false:
queueLock.acquire() # 获取锁,用于线程同步
if not workQueue.empty():
data = quit.get()
queueLock.release() # 释放锁,开启下一个线程
print ("%s 处理 %s" % (run_name, data))
else:
queueLock.release() # 释放锁,开启下一个线程
time.sleep(0.5)
class foo(threading.Thread): #单继承threading.Thread
def __init__(self,name,quit): #定义构造方法,参数通过 __init__() 传递到类的实例化操作上。
threading.Thread.__init__(self) #调用threading.Thread父类的构函
self.run_name = name
self.exit = quit
def run(self): #threading.Thread父类里的方法,start()启动线程的时候,会调用这个run方法
print ("线程名称:"+self.run_name)
run_data(self.run_name,self.exit)
print ("结束线程:"+self.run_name)
threadList = ["线程-1", "线程-2","线程-3","线程-4"]
number = ["1", "2", "3", "4", "5","6","7","8","9","10","11","12"]
queueLock = threading.Lock()
workQueue = queue.Queue(100) # 定义消息队列qsize,太小get取元素时可能会阻塞
threads = [] # 初始化线程列表
# 创建新线程
for run_name in threadList:
thread = foo(run_name, workQueue) # 创建新线程
thread.start() # 开启新线程
threads.append(thread) # 添加线程到线程列表
# 填充队列
queueLock.acquire() # 获取锁,用于线程同步
for count in number:
workQueue.put(count) # 往消息队列里存放数据,可放qsize = 100
queueLock.release() # 释放锁,开启下一个线程
# 等待队列清空
while not workQueue.empty(): #判断消息队列是否为空,
pass
# 通知线程是时候退出
false = 1
# 等待所有线程完成
for t in threads:
t.join() # 有关 threading 的join() 函数详解,可以查一下,强迫症患者修的福报。
print ("退出主线程")