帮我写个python脚本:创建三个线程,第一个线程循环打印字符串,第二个线程在窗口中打印第一个线程的输出,第三个线程监听按键事件,如果按下空格键,退出所有线程
时间: 2023-05-13 20:07:45 浏览: 108
好的,以下是 Python 代码:
```python
import threading
import msvcrt
class Thread1(threading.Thread):
def run(self):
while True:
print("Hello, world!")
class Thread2(threading.Thread):
def __init__(self, thread1):
super().__init__()
self.thread1 = thread1
def run(self):
while True:
print(self.thread1.stdout.readline().decode(), end='')
class Thread3(threading.Thread):
def __init__(self, thread1, thread2):
super().__init__()
self.thread1 = thread1
self.thread2 = thread2
def run(self):
while True:
if msvcrt.getch() == b' ':
self.thread1.terminate()
self.thread2.terminate()
break
thread1 = Thread1()
thread2 = Thread2(thread1)
thread3 = Thread3(thread1, thread2)
thread1.start()
thread2.start()
thread3.start()
```
这个脚本创建了三个线程,第一个线程循环打印字符串 "Hello, world!",第二个线程在窗口中打印第一个线程的输出,第三个线程监听按键事件,如果按下空格键,就会退出所有线程。
阅读全文