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

相关推荐
2401_8414956430 分钟前
【自然语言处理】轻量版生成式语言模型GPT
人工智能·python·gpt·深度学习·语言模型·自然语言处理·transformer
云和数据.ChenGuang1 小时前
tensorflow生成随机数和张量
人工智能·python·tensorflow
测试老哥2 小时前
python+requests+excel 接口测试
自动化测试·软件测试·python·测试工具·测试用例·excel·接口测试
AI纪元故事会2 小时前
冰泪与雨丝:一个AI的Python挽歌
开发语言·人工智能·python
ColderYY2 小时前
Python连接MySQL数据库
数据库·python·mysql
寒秋丶2 小时前
Milvus:数据库层操作详解(二)
数据库·人工智能·python·ai·ai编程·milvus·向量数据库
凯歌的博客3 小时前
python虚拟环境应用
linux·开发语言·python
西柚小萌新3 小时前
【深入浅出PyTorch】--8.1.PyTorch生态--torchvision
人工智能·pytorch·python
MonkeyKing_sunyuhua3 小时前
can‘t read /etc/apt/sources.list: No such file or directory
python
多喝开水少熬夜4 小时前
损失函数系列:focal-Dice-vgg
图像处理·python·算法·大模型·llm