Python编程实践 - 多线程

简介

本文介绍在Python中如何实现多线程,包含如下要点:

  1. 面向对象的继承,实现自定义的多线程类
  2. 队列的使用,包括队列的初始化、赋值、取数
一、 面向对象的继承,实现自定义的多线程类

继承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 ("退出主线程")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

修破立生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值