首页 > 解决方案 > 在python中暂停线程

问题描述

如果按下某个键,我想暂停并继续线程。我试过:如果按下 q,它将删除(更改为 0)“time.sleep(99999)”,但它没有用任何人都可以帮助我吗?

import keyboard
from threading import Thread
from time import sleep

Thread1 = True
Thread2 = True

class main():
    def test1():
        if keyboard.is_pressed("q"):      #if keyboard is pressed q it will reomve the sleep
            time = 0
        time = 99999

        while Thread1 == True:
            print("Thread1")
            sleep(time)
    def test2():
        while Thread2 == True:
            print("Thread2")
            sleep(1)
        
    Thread(target=test1).start()
    Thread(target=test2).start()
    
main()

标签: pythonpython-3.xmultithreadingkeyboardpython-multithreading

解决方案


您可以为此创建一个类

class customThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        super(customThread, self).__init__(*args, **kwargs)
        self.__stop_event = threading.Event()
        
    def stop(self):
        self.__stop_event.set()
    def stoppped(self):
        self.__stop_event.is_set()

我们将stop()在用户点击时调用该函数q

def test1():
    if keyboard.is_pressed("q"):  
        Thread1.stop()  

推荐阅读