import threading
from queue import Queue
class ThreadPush(threading.Thread):
def __init__(self, threadName, my_queue):
# 繼承父類的方法
super(ThreadPush, self).__init__()
self.threadName = threadName # 線程名字
self.my_queue = my_queue
def run(self):
print('啟動' + self.threadName)
while True:
try:
id = self.my_queue.get(False) # False 如果隊列為空,拋出異常
except Exception as e:
print('隊列為空 ', e)
return
print(id)
def main():
my_queue = Queue()
for i in range(100):
my_queue.put(i)
thread_name = []
for id in range(1, 3):
name = '線程{}'.format(id)
thread_name.append(name)
# 初始化線程
thread_list = []
for threadName in thread_name:
thread = ThreadPush(threadName, my_queue)
thread_list.append(thread)
# 啟動線程
for thread in thread_list:
thread.start()
# join: 等待線程執行完畢
for thread in thread_list:
thread.join()
if __name__ == '__main__':
main()