含有章节索引的中文 文章模板 -- Zoom.Quiet [DateTime(2004-08-09T23:58:48Z)]

TableOfContents

Python线程研究

外部文章链接

个人经验汇集

hoxide

Limodou

Zoom.Quiet

Dreamingk

   1 ###        thread_example.py
   2 import time
   3 import thread
   4 def timer(no,interval):                                                         #自己写的线程函数
   5         while True:
   6                 print 'Thread :(%d) Time:%s'%(no,time.ctime())
   7                 time.sleep(interval)
   8 def test():
   9         thread.start_new_thread(timer,(1,1))                          #使用thread.start_new_thread()来产生2个新的线程
  10         thread.start_new_thread(timer,(2,3))
  11 if __name__=='__main__':
  12         test()

这个是

thread.start_new_thread(function,args[,kwargs])

函数原型,其中function参数是你将要调用的线程函数;args是讲传递给你的线程函数的参数,他必须是个tuple类型;而kwargs是可选的参数。 线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit(),他抛出SystemExit exception,达到退出线程的目的。

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

其实thread和threading的模块中还包含了其他的很多关于多线程编程的东西,例如锁、定时器、获得激活线程列表等等,请大家仔细参考python的文档!