以下是一个示例:
import threading
import time
# 定义一个线程类
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.running = True
def run(self):
while self.running:
# 执行活动的代码
print("活动正在运行...")
time.sleep(1)
def stop(self):
self.running = False
# 创建一个线程实例并启动
thread = MyThread()
thread.start()
# 主线程等待用户输入,直到用户输入"stop"时停止线程
while True:
command = input("输入命令: ")
if command == "stop":
thread.stop()
break
这个示例使用了Python的threading
模块来创建一个线程类MyThread
,其中run
方法是线程的主体,它不断地执行活动的代码。stop
方法用于停止线程。
在主线程中,我们创建了一个线程实例thread
并启动它。然后,主线程进入一个循环,等待用户输入命令。当用户输入"stop"时,主线程调用stop
方法停止线程,并跳出循环。
通过这种方式,活动可以保持运行,直到用户输入"stop"命令。你可以根据需要修改run
方法的代码来执行你想要的活动。