Python threading多线程编程+queue实现线程间的变量共享
threading:
- 直接调用threading.Thread()创建子线程
- 通过继承threading.Thread,自定义Thread类实现实例化创建子线程
queue:
- queue利用阻塞实现了线程安全
- 创建queue后,利用global关键字在类或者函数内部实现共享
import threading
import time
from queue import Queue
music_album = ['One hundred miles', 'Two hundred miles', 'Three hundred miles', 'Four hundred miles',
'Five hundred miles', 'Six hundred miles', 'Seven hundred miles', 'Eight hundred miles',
'Nine hundred miles', 'Ten hundred miles', ]
q = Queue(3)
class Music_Cols(threading.Thread):
def __init__(self, name):
super().__init__(name=name)
def run(self):
global music_album
global q
num = 0
while True:
try:
music = music_album[num]
q.put(music)
except IndexError:
break
num += 1
class Music_Play(threading.Thread):
def __init__(self, name):
super().__init__(name=name)
def run(self):
global q
while True:
if q.not_empty:
music = q.get()
print('{}正在播放{}'.format(threading.current_thread(), music))
time.sleep(20)
q.task_done()
print('{}播放结束'.format(music))
else:
break
if __name__ == '__main__':
mc_thread = Music_Cols('music_cols')
mc_thread.setDaemon(True)
mc_thread.start()
for i in range(10):
mp_thread = Music_Play('music_play')
mp_thread.setDaemon(True)
mp_thread.start()
q.join()