本文介绍在Python中如何实现多线程,包含如下要点:
继承threading.Thread类,并实现__init__
方法和run
方法
class myThread (threading.Thread):
def __init__(self, threadID, threadName, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.threadName = threadName
self.q = q
def run(self):
print ("开启线程:" + self.name)
self.process_data()
print ("退出线程:" + self.name)
队列的特性是先进先出,可保证处理的顺序性。如果没有顺序性的要求,也可以用列表、数组等来替代。
# 队列初始化,队列大小有日期列表的长度而定
work_queue = queue.Queue(len(date_list))
# 队列赋值
for word in date_list:
work_queue.put(word)
# 队列中取数
data = work_queue.get()
# coding=utf-8
import os
import string
import pandas as pd
import queue
import threading
import time
class MyThread (threading.Thread):
def __init__(self, thread_id, thread_name, work_queue):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.thread_name = thread_name
self.work_queue = work_queue
def run(self):
print ("开启线程:" + self.thread_name)
self.process_data()
print ("退出线程:" + self.thread_name)
def process_data(self):
while not exitFlag:
if not self.work_queue.empty():
## 从队列中取出一个数据对象
data = self.work_queue.get()
print ("%s processing %s" % (self.thread_name, data))
time.sleep(1)
if __name__ == '__main__':
## 用于标识是否结束线程,当exitFlag = 1时,结束线程
exitFlag = 0
thread_num = 3
start_date = '20210101'
end_date = '20210201'
date_list = pd.date_range(start=start_date, end=end_date, freq="D")
# 队列初始化,队列大小有日期列表的长度而定
work_queue = queue.Queue(len(date_list))
# 队列赋值
for word in date_list:
work_queue.put(word)
threads = []
# 创建新线程
for thread_id in range(1, thread_num+1):
thread_name = 'Thread-%d'%thread_id
thread = MyThread(thread_id, thread_name, work_queue)
thread.start()
threads.append(thread)
# 等待队列清空
while not work_queue.empty():
pass
# 通知线程是时候退出
exitFlag = 1
# 等待所有线程完成
for t in threads:
t.join()
print ("退出主线程")