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看效果,可以打开测试结束看效果,反正我不知道什么原理。

相关推荐
Dxy12393102161 小时前
Python 条件语句详解
开发语言·python
龙泉寺天下行走1 小时前
Python 翻译词典小程序
python·oracle·小程序
践行见远1 小时前
django之视图
python·django·drf
love530love2 小时前
Windows避坑部署CosyVoice多语言大语言模型
人工智能·windows·python·语言模型·自然语言处理·pycharm
掘金-我是哪吒4 小时前
分布式微服务系统架构第132集:Python大模型,fastapi项目-Jeskson文档-微服务分布式系统架构
分布式·python·微服务·架构·系统架构
xhdll4 小时前
egpo进行train_egpo训练时,keyvalueError:“replay_sequence_length“
python·egpo
Cchaofan5 小时前
lesson01-PyTorch初见(理论+代码实战)
人工智能·pytorch·python
网络小白不怕黑5 小时前
Python Socket编程:实现简单的客户端-服务器通信
服务器·网络·python
Ronin-Lotus5 小时前
程序代码篇---python获取http界面上按钮或者数据输入
python·http
不知道写什么的作者5 小时前
Flask快速入门和问答项目源码
后端·python·flask