Python多线程启动和停止

Python多线程启动和停止,python,multithreading,Python,Multithreading,我用Python编写了一个关于线程的程序,如下所示。但是,线程似乎没有运行。当我运行程序时,它显示消息“线程已完成”。我做错了什么 #!/usr/bin/python from threading import Thread class timer: def __init__(self): self._running = True def terminate(self): self._running = False

我用Python编写了一个关于线程的程序,如下所示。但是,线程似乎没有运行。当我运行程序时,它显示消息“线程已完成”。我做错了什么

#!/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
#/usr/bin/python
从线程导入线程
类计时器:
定义初始化(自):
self.\u running=True
def终止(自我):
self.\u running=False
def运行(自身,n):
mycount=0
#当self.\u运行时:
当mycount<10时:
mycount=mycount+1
打印(n)
#开线
c=计时器()
t=Thread(target=c.run,args=(“One!!”,)
t、 开始
而(一):
如果t.还活着():
打印(“线程仍在运行”)
其他:
打印(“线程完成”)
mya=原始输入(“输入,a=停止线程b=启动线程c=退出程序”)
如果mya==“a”:
c、 终止()
如果mya==“b”:
c=计时器()
t=Thread(target=c.run,args=(“两个!!”,)
t、 开始
如果mya==“c”:
打破

将while-loop-in-run方法更改为:

while mycount < 10:
    mycount=mycount+1
    time.sleep(1) # sleep for 1 second
print(n)
当mycount<10时:
mycount=mycount+1
时间。睡眠(1)#睡眠1秒
打印(n)
不要忘记在脚本开头导入时间模块。 这样,线程将循环10秒。使用
t.Start()启动线程

@蒂姆·卡斯特利恩斯建议。

t.start()
而不是
t.start
即使有一个适当的
start
调用,
run
函数可能需要一个
时间。sleep(0.1)
大约需要一些“实时”时间来完成……我已经将代码修改为t.start(),并在run函数中添加了time.sleep(0.5),它可以启动线程。但是,即使我添加了“c.terminate()”线程也无法停止,那么,如何停止线程呢??谢谢你的线程将每秒循环一次,如果他不调用
t.start()
properlytanks,它甚至不会启动,它可以根据你的评论启动线程。但是,当我将上面的代码更改为:While self.\u running时,如何终止线程