from threading import *import time class MyThread(Thread):def run (self):self.ifdo = True while self.ifdo:print 'I am running...'time.sleep(0.1) def stop (self):print 'I will stop it...'self.ifdo = False tr = MyThread()tr.setDaemon(True)tr.start()time.sleep(1)tr.stop()tr.join()
这样就更直观了
from threading import *import time class MyThread(Thread):def run (self):self.ifdo = True while self.ifdo:print 'I am running...'time.sleep(2) def stop (self):print 'I am stopping it...'self.ifdo = False tr = MyThread()tr.setDaemon(True)tr.start()print 'I will stop it...'time.sleep(5)tr.stop()tr.join()
Python用sleep停止一个线程的运行,而不影响主线程的运行,案例代码如下:from threading import *import time class MyThread(Thread):def run (self):self.ifdo = True while self.ifdo:print 'I am running...'time.sleep(2) def stop (self):print 'I am stopping it...'self.ifdo = Falsetr = MyThread()tr.setDaemon(True)tr.start()print 'I will stop it...'time.sleep(5)tr.stop()tr.join()