停止后,多线程继续工作(Python

时间:2019-04-27 12:55:11

标签: python multithreading

我写了一些带有while循环的代码。然后,我把它放在readread上。当我想停止线程时,我将更改while循环的条件,并且它将停止。但是当我想在停顿后继续时,我做不到。

我试图使其递归。但是,这需要处理器时间。我该怎么做呢?

class Some_class():
    def __init__(self):
        self.while_condition = True
        self.mythread = Thread(target=self.do_trade)

    def start(self):
        if self.while_condition = False:
            self.while_condition = True
        else: 
            self.mythread.start()

    def stop(self):
        self.while_condition = False

    def do_action(self):
        while(self.while_condition):
            print("thread is working")
            time.sleep(5)
        print("action stopped")
        self.do_action()
obj = Some_class()

我期望输出:

  

线程正在工作

     

线程正在工作

obj.stop()之后

  

操作已停止

然后obj.start()将继续

  

线程正在工作

     

线程正在工作

1 个答案:

答案 0 :(得分:2)

您的代码中有很多错误的地方,请检查下面的正确代码并找出错误所在:

请注意,线程只能启动一次且无法重新启动,因此您每次都启动新线程

from threading import Thread
import time

class Some_class():
    def __init__(self):
        self.while_condition = True

    def start(self):
        self.while_condition = True
        Thread(target=self.do_action).start()

    def stop(self):
        self.while_condition = False

    def do_action(self):
        while(self.while_condition):
            print("thread is working")
            time.sleep(5)
        print("action stopped")
obj = Some_class()
obj.start()
time.sleep(10)
obj.stop()
time.sleep(5)
print('restarting thread')
obj.start()

输出:

thread is working
thread is working
action stopped
restarting thread
thread is working
thread is working
thread is working