使用threading.Thread模块,也有两种使用方法,可以用类,也可以在实例化对象中传入函数或类实例。
#!/usr/bin/env python # -*- coding: utf-8 -*- from threading import Thread import time def run_thread(n): for i in range(n): print i class race(Thread): def __init__(self,threadname,interval): Thread.__init__(self,name=threadname) self.interval = interval self.isrunning = True def run(self): while self.isrunning: print 'thread %s is running,time:%s\n' %(self.getName(),time.ctime()) time.sleep(self.interval) def stop(self): self.isrunning = False def test(): t1 = Thread(target=run_thread,args=(5,)) t1.start() thread1 = race('A',1) thread2 = race('B',2) thread1.start() thread2.start() time.sleep(4) thread1.stop() thread2.stop() if __name__ == '__main__': test()