利用多线程机制编写程序,输出一个问候语,要求每隔1秒钟输出一个字符。用2种方法分别创建线程。
时间: 2024-03-06 12:49:35 浏览: 17
方法一:使用Thread类创建线程
```python
import threading
import time
def print_char(char):
while True:
print(char, end='')
time.sleep(1)
if __name__ == '__main__':
thread1 = threading.Thread(target=print_char, args=('H',))
thread2 = threading.Thread(target=print_char, args=('i',))
thread1.start()
thread2.start()
```
方法二:使用继承Thread类的子类创建线程
```python
import threading
import time
class PrintCharThread(threading.Thread):
def __init__(self, char):
super().__init__()
self.char = char
def run(self):
while True:
print(self.char, end='')
time.sleep(1)
if __name__ == '__main__':
thread1 = PrintCharThread('H')
thread2 = PrintCharThread('i')
thread1.start()
thread2.start()
```