Python多线程编程方式1(转)

通过调用threading模块继承threading.Thread类来包装一个线程对象。

 1 #!/usr/bin/env python
 2 #thread_example2.py
 3 import threading
 4 import time
 5 class timer(threading.Thread):        #我的timer类继承自threading.Thread类   
 6     def __init__(self,no,interval):    
 7         #在我重写__init__方法的时候要记得调用基类的__init__方法   
 8         threading.Thread.__init__(self)        
 9         self.no=no   
10         self.interval=interval   
11  
12     def run(self):  #重写run()方法,把自己的线程函数的代码放到这里
13         i = 4
14         while i > 0:
15             print(i)
16             print('Thread Object (%d), Time:%s'%(self.no,time.ctime()))
17             time.sleep(self.interval)
18             i = i - 1
19 
20 def test():   
21     threadone=timer(1,1)    #产生2个线程对象   
22     threadtwo=timer(2,3)   
23     threadone.start()   #通过调用线程对象的.start()方法来激活线程   
24     threadtwo.start()   
25        
26 if __name__=='__main__':   
27     test()  

其实如果时间充足的话我还是建议多看看源码,多点耐心,就会有意外的收获

posted on 2014-01-04 22:57  rhythmer  阅读(149)  评论(0编辑  收藏  举报

导航