python多线程

来源:互联网 发布:淘宝网店怎么上架宝贝 编辑:程序博客网 时间:2024/06/04 10:49

转自:http://www.cnblogs.com/tqsummer/archive/2011/01/25/1944771.html

一、Python中的线程使用:

Python中使用线程有两种方式:函数或者用类来包装线程对象。

1、  函数式:调用thread模块中的start_new_thread()函数来产生新线程。如下例:

view plaincopy to clipboardprint?import time  import thread  def timer(no, interval):      cnt = 0      while cnt<10:          print 'Thread:(%d) Time:%s\n'%(no, time.ctime())          time.sleep(interval)          cnt+=1      thread.exit_thread()          def test(): #Use thread.start_new_thread() to create 2 new threads      thread.start_new_thread(timer, (1,1))      thread.start_new_thread(timer, (2,2))     if __name__=='__main__':      test()  

上面的例子定义了一个线程函数timer,它打印出10条时间记录后退出,每次打印的间隔由interval参数决定。thread.start_new_thread(function, args[, kwargs])的第一个参数是线程函数(本例中的timer方法),第二个参数是传递给线程函数的参数,它必须是tuple类型,kwargs是可选参数。

线程的结束可以等待线程自然结束,也可以在线程函数中调用thread.exit()或thread.exit_thread()方法。

      2、创建threading.Thread的子类来包装一个线程对象,如下例:

import threading  import time  class timer(threading.Thread): #The timer class is derived from the class threading.Thread      def __init__(self, num, interval):          threading.Thread.__init__(self)          self.thread_num = num          self.interval = interval          self.thread_stop = False         def run(self): #Overwrite run() method, put what you want the thread do here          while not self.thread_stop:              print 'Thread Object(%d), Time:%s\n' %(self.thread_num, time.ctime())              time.sleep(self.interval)      def stop(self):          self.thread_stop = True              def test():      thread1 = timer(1, 1)      thread2 = timer(2, 2)      thread1.start()      thread2.start()      time.sleep(10)      thread1.stop()      thread2.stop()      return     if __name__ == '__main__':      test()  

就我个人而言,比较喜欢第二种方式,即创建自己的线程类,必要时重写threading.Thread类的方法,线程的控制可以由自己定制。

threading.Thread类的使用:

1,在自己的线程类的__init__里调用threading.Thread.__init__(self, name = threadname) Threadname为线程的名字

2, run(),通常需要重写,编写代码实现做需要的功能。

3,getName(),获得线程对象名称

4,setName(),设置线程对象名称

5,start(),启动线程

6,jion([timeout]),等待另一线程结束后再运行。

7,setDaemon(bool),设置子线程是否随主线程一起结束,必须在start()之前调用。默认为False。

8,isDaemon(),判断线程是否随主线程一起结束。

9,isAlive(),检查线程是否在运行中。

    此外threading模块本身也提供了很多方法和其他的类,可以帮助我们更好的使用和管理线程。可以参看http://www.python.org/doc/2.5.2/lib/module-threading.html。




原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 小孩米粉吃多了怎么办 宝宝四个月了奶水不足怎么办 4个月奶水不足怎么办 孩子不吃奶粉母乳又不够怎么办 宝宝吃母乳上火了怎么办 5个月宝宝厌奶期怎么办 九个月宝宝不吃奶粉怎么办 第5个月奶不够吃怎么办 九个月的宝宝不吃奶粉怎么办 9个月宝宝不肯吃怎么办 11个月不吃辅食怎么办 4个月母乳不足怎么办 宝宝四个月奶不够怎么办 四个月宝宝奶不够吃怎么办 宝宝吃母乳偏瘦怎么办 宝宝吃母乳很瘦怎么办 8个月宝宝流汗太多怎么办 奶水多乳房胀疼怎么办 乳房胀奶奶水减少怎么办 宝宝五个月奶水不够吃怎么办 梦见鬼在梦里怎么办 宝宝晚上奶水不够吃怎么办 十个月晚上奶水不够吃怎么办 产妇晚上奶水不够吃怎么办 刚出生的宝宝不吃母乳怎么办 宝宝六个月奶不够吃怎么办 六个月奶不够吃怎么办 刚出生奶不够吃怎么办 做梦醒了看见鬼怎么办 宝宝到陌生地方哭闹怎么办 大人生病住院小孩没人带怎么办 孕妇被小猫抓了怎么办 怀孕了家里有猫怎么办 厕所被湿纸巾堵了怎么办 5天新生儿不拉屎怎么办 4月宝宝不拉屎怎么办 两岁宝宝晚上睡觉哭闹怎么办 2月婴儿吐奶很多怎么办 心情不好回奶了怎么办 四个月了没奶怎么办 八岁宝宝还尿床怎么办