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

相关推荐
Mason Lin40 分钟前
2025年1月22日(网络编程 udp)
网络·python·udp
清弦墨客1 小时前
【蓝桥杯】43697.机器人塔
python·蓝桥杯·程序算法
RZer3 小时前
Hypium+python鸿蒙原生自动化安装配置
python·自动化·harmonyos
CM莫问4 小时前
什么是门控循环单元?
人工智能·pytorch·python·rnn·深度学习·算法·gru
查理零世4 小时前
【算法】回溯算法专题① ——子集型回溯 python
python·算法
圆圆滚滚小企鹅。5 小时前
刷题记录 HOT100回溯算法-6:79. 单词搜索
笔记·python·算法·leetcode
纠结哥_Shrek5 小时前
pytorch实现文本摘要
人工智能·pytorch·python
李建军6 小时前
TensorFlow 示例摄氏度到华氏度的转换(二)
人工智能·python·tensorflow
李建军6 小时前
TensorFlow 示例摄氏度到华氏度的转换(一)
人工智能·python·tensorflow
2301_793069826 小时前
npm 和 pip 安装中常见问题总结
开发语言·python