Python3 之 线程 及线程中的锁、队列 - 基础案例

Python3 之 线程 及线程中的锁、队列 - 基础案例

前言

小白个人研究成功,仅作为笔记方便翻阅,仅供参考
首先要继承父类threading.Thread,重写init和run方法,以前貌似有thread.Thread但python3已经没有了

一、完整代码

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
import threading
import time
import queue


# 创建一个线程类并继承threading.Thread
class MyThread(threading.Thread):
    # 重写init和run方法(参数:线程名称)
    def __init__(self, threadName):
        threading.Thread.__init__(self)
        self.threadName = threadName

    def run(self):
        print('开启的线程是:', self.threadName)
        print_time(self.threadName)
        print('结束的线程是:', self.threadName)


def print_time(threadName):
    while not exitFlag:
        # 开启锁 (不加锁则是同时执行,加锁则是一个一个执行)
        threadLock.acquire()
        if not workQueue.empty():
            # 获取队列(不同于list,获取后队列中将不再保存该数据)
            index = workQueue.get()
            # 格式化时间,方便查看
            nowTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
            print('%s - %s线程正在执行第%d次' % (nowTime, threadName, index))
        # 释放锁
        threadLock.release()
        # 强制休眠1秒
        time.sleep(1)


# 创建线程锁
threadLock = threading.Lock()
# 创建队列
workQueue = queue.Queue(5)
threads = []
threadsName = ['长江一号', '黄河无敌贰号', '银河宇宙超级无敌三号']
numList = [1, 2, 3, 4, 5]
exitFlag = 0

if __name__ == '__main__':
    # 创建线程
    for tName in threadsName:
        thread = MyThread(tName)
        # 执行线程
        thread.start()
        threads.append(thread)

    # 填充队列
    for num in numList:
        workQueue.put(num)

    # 等待队列清空 (不加这一段print_time函数的if条件非debug模式下进不去,具体为什么我没有弄明白)
    while not workQueue.empty():
        pass

    # 结束
    exitFlag = 1

    # 等待所有线程执行完成
    for i in threads:
        i.join()

    print('全部执行完成!')


总结

队列光从字面理解,我觉得完全ok,但是实际操作的时候有很多地方觉得很迷,不太明白比如while not workQueue.empty(): pass;这一段话看着毫无意义,但是我不加的话,我的 if not workQueue.empty()就进不去,就像时间太赶,来不及进去一样(因为我debug模式,一行一行进完全ok),我也试过调长休眠时间但是也没用,一定要写while 而且里面是个没用的pass,这一点实在是有点无法理解。附上我参考的地址:https://www.runoob.com/python/python-multithreading.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值