这里发布了一个解决方案来创建一个可停止的线程。但是,我在理解如何实施此解决方案时遇到了一些问题。
使用代码...
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
Run Code Online (Sandbox Code Playgroud)
如何创建一个线程来运行每 1 秒向终端打印一次“Hello”的函数。5 秒后,我使用 .stop() 停止循环函数/线程。
我再次在理解如何实现这个停止解决方案时遇到了麻烦,这是我目前所拥有的。
import threading
import time
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def …Run Code Online (Sandbox Code Playgroud)