多线程时钟代码
时间: 2023-06-28 22:04:22 浏览: 32
以下是一个基本的多线程时钟代码示例,它使用 Python 的 threading 模块:
```python
import threading
import time
class ClockThread(threading.Thread):
def __init__(self, interval):
threading.Thread.__init__(self)
self.interval = interval
self.alive = False
def run(self):
self.alive = True
while self.alive:
print(time.strftime("%H:%M:%S", time.localtime()))
time.sleep(self.interval)
def stop(self):
self.alive = False
if __name__ == "__main__":
clock_thread = ClockThread(1)
clock_thread.start()
time.sleep(10)
clock_thread.stop()
```
这个代码创建了一个名为 ClockThread 的类,该类继承自 threading.Thread 类,它使用 run() 方法实现了一个简单的时钟,该时钟每隔一秒打印当前时间。start() 方法启动线程,stop() 方法停止线程。在主程序中,创建了一个 ClockThread 对象并启动它,等待 10 秒后停止它。