import threading import sys global tickt_count = 0 class MyThread(threading.Thread): def __init__(self,name): threading.Thread.__init__(self,name=name) self.name = name self.tickts = 0 def run(self): while True: if (tickt_count>0): tickt_count -= 1 self.tickts += 1 print("%s售票机售出第%d号"%(self.name,tickt_count)) else: sys.exit(0) t1 = MyThread('Window1') t1.start() t2 = MyThread('Window2') t2.start() t3 = MyThread('Windou3') t3.start()这段代码为何出错
时间: 2023-11-27 07:53:28 浏览: 69
Python RuntimeError: thread.__init__() not called解决方法
这段代码出错的原因是变量 `tickt_count` 没有被正确定义。应该将 `global tickt_count = 0` 改为 `tickt_count = 100`,并且应该在定义 `MyThread` 类之前。正确的代码应该如下所示:
```python
import threading
import sys
tickt_count = 100
class MyThread(threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self,name=name)
self.name = name
self.tickts = 0
def run(self):
while True:
if (tickt_count>0):
tickt_count -= 1
self.tickts += 1
print("%s售票机售出第%d号"%(self.name,tickt_count))
else:
sys.exit(0)
t1 = MyThread('Window1')
t1.start()
t2 = MyThread('Window2')
t2.start()
t3 = MyThread('Windou3')
t3.start()
```
这样就能正确地运行了。
阅读全文