python - 在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()
解决方案
您可以为此创建一个类
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()
推荐阅读
- go - 如何在使用站点变量时访问 Hugo 模板中的动态属性
- node.js - nestjs 节点模块问题,如何在nestjs 中使用when/sequence 模块
- java - 计算 Firestore 集合中的 pendingDocumentWrite 总数
- linux - Pop_os:如何为 intellij 创建命令行启动器
- sql-server - 使用 FLWOR 从另一个表中获取数据
- javascript - 如何突出显示在 div 中的字符串中的特定文本?
- javascript - Js按attr按字母顺序排序不起作用
- javascript - 如何在 .where 之后访问 firestore 中的子集合
- c++ - 默认构造函数参数错误 - 'Autoturism::Autoturism(char *,unsigned int)':无法将参数 1 从 'const char [6]' 转换为 'char *'
- python - 在同一索引上附加项目