设计两个自定义线程,名字分别是自己姓名的缩写和自己的学号 让他们和主线程公平竞争、用继承Thread类和实施Runnable 接口分别实现一遍。
时间: 2023-11-27 09:49:37 浏览: 74
继承Thread类实现:
```python
import threading
class MYThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
for i in range(5):
print("This is thread %s, running %d" % (self.name, i))
if __name__ == "__main__":
t1 = MYThread("ZJL")
t2 = MYThread("20210000000000")
t1.start()
t2.start()
t1.join()
t2.join()
print("All threads finished")
```
实现Runnable接口:
```python
import threading
class MYRunnable(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
for i in range(5):
print("This is thread %s, running %d" % (self.name, i))
if __name__ == "__main__":
t1 = threading.Thread(target=MYRunnable("ZJL").run)
t2 = threading.Thread(target=MYRunnable("20210000000000").run)
t1.start()
t2.start()
t1.join()
t2.join()
print("All threads finished")
```
注:在实现Runnable接口时,需要通过`target`参数传入要执行的函数。
阅读全文