我在Python中编写了一个关于线程的程序,如下所示。但是,似乎线程没有运行。当我运行程序时,它会显示消息" Thread Completed"。我做错了什么?
#!/usr/bin/python
from threading import Thread
class timer:
def __init__(self):
self._running = True
def terminate(self):
self._running = False
def run(self, n):
mycount=0
#while self._running:
while mycount < 10:
mycount=mycount+1
print(n)
#start a thread
c = timer()
t = Thread(target=c.run, args=("One!!",))
t.start
while(1):
if t.is_alive():
print("Thread still running")
else:
print("Thread Completed")
mya=raw_input("Input, a=stop thread b=start thread c=quit program ")
if mya=="a":
c.terminate()
if mya=="b":
c = timer()
t = Thread(target=c.run, args=("Two!!",))
t.start
if mya=="c":
break
答案 0 :(得分:0)
将run方法中的循环更改为:
while mycount < 10:
mycount=mycount+1
time.sleep(1) # sleep for 1 second
print(n)
不要忘记在脚本开头导入时间模块。
这样,你的线程将循环10秒。以t.start()
为开头线程
@Tim Castelijns建议。