Python 使用线程启动类方法实现暂停与结束案例

定义测试执行类Tester.py

python 复制代码
# 执行试验类
import time

class Tester(object):
    def __init__(self, jobName, stepList):
        self.jobName = jobName
        self.stepList = stepList

    # 开始执行
    def start(self, flag):
        print(f'{self.jobName} start')
        self.status = "start"

        stepIndex = 0
        while not flag.isSet() and self.status != "stop":
            if self.status == "start":
                step = self.stepList[stepIndex]
                print(f"{self.jobName} run step: {step}")
                stepIndex += 1
            if stepIndex >= len(self.stepList):
                self.status = "stop"
            time.sleep(1)

    def stop(self):
        self.status = "stop"
        self.stepList = []
        self.jobName = ""

    def pause(self):
        self.status = "pause"

    def reStart(self):
        self.status = "start"

执行主类ACClient.py

python 复制代码
from obj.Tester import Tester
import threading
import time

tester = Tester("AJob", ['a','b','c','d','e','f','g','h'])
testerB = Tester("BJob", ['a','b','c','d','e','f','g','h'])

# 创建线程,目标是my_instance的my_method方法,并传入参数
flag = threading.Event()
thread = threading.Thread(target=tester.start, args=(flag, ))
# 启动线程
thread.start()

# 创建线程,目标是my_instance的my_method方法,并传入参数
flagB = threading.Event()
threadB = threading.Thread(target=testerB.start, args=(flagB, ))
# 启动线程
threadB.start()
print("====================")

# 测试结束
# time.sleep(1)
# flag.set();

# 测试暂停
time.sleep(2)
tester.pause()
time.sleep(10)
tester.reStart() # 10秒后继续

print("====================")

有点懒得解释,写完之后,执行主类ACClient.py看效果,可以打开测试结束看效果,反正我不知道什么原理。

相关推荐
橡晟4 小时前
深度学习入门:让神经网络变得“深不可测“⚡(二)
人工智能·python·深度学习·机器学习·计算机视觉
墨尘游子4 小时前
神经网络的层与块
人工智能·python·深度学习·机器学习
倔强青铜34 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
企鹅与蟒蛇5 小时前
Ubuntu-25.04 Wayland桌面环境安装Anaconda3之后无法启动anaconda-navigator问题解决
linux·运维·python·ubuntu·anaconda
autobaba5 小时前
编写bat文件自动打开chrome浏览器,并通过selenium抓取浏览器操作chrome
chrome·python·selenium·rpa
Rvelamen6 小时前
LLM-SECURITY-PROMPTS大模型提示词攻击测评基准
人工智能·python·安全
【本人】6 小时前
Django基础(一)———创建与启动
后端·python·django
SHIPKING3938 小时前
【python】基于pygame实现动态粒子爱心
开发语言·python·pygame
kk_stoper9 小时前
如何通过API查询实时能源期货价格
java·开发语言·javascript·数据结构·python·能源
java1234_小锋9 小时前
【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 架构搭建
python·自然语言处理·flask