python多线程

python多线程有两种用法,一种是在函数中使用,一种是放在类中使用

1、在函数中使用

定义空的线程列表

threads=[]

创建线程

t=threading.Thread(target=函数名,args=(函数参数,必须为元组类型))#若函数中没有参数,则args参数可省略不写

将线程加到线程列表中

threads.append(t)

运行线程

for t in threads:

  t.setDaemon(True)  #这个也是守护线程,与join方法不同的是,它守护的是主线程,而join方法守护的是子线程。可以理解为这两个方法的作用正好相反。

  t.start()

for t in threads:

  t.join()    #守护线程,join()可以传参,如join(5),表示超过5s就会直接跳出线程,直接执行下面的代码

2、创建线程类

class MyThread(threading.Thread):

  def __init__(self,func,args):

    super(MyThread,self).__init__() #super 方法是python中类子类继承父类用到的方法,可以保证父类中的方法只被调用一次。另一种写法是直接用父类名调用,效果是一样的。threading.Thread.__init__(self)

    self.func=func

    self.args=args

  def run(self):

    self.func(*self.args)

def print_boy(num):

  for i in range(num):

    print "I am boy %s,Now the time is:%s"%(i,time.strftime("%H:%M:%S"))

    time.sleep(4)

创建空的线程列表

threads=[]

创建线程

t=MyThread(print_boy,(3,)) #注意这里传参的时候,必须是元组的形式

加入线程列表

threads.append(t)

运行线程
for t in threads:

  t.start()

for t in threads:

  t.join()

 

posted @ 2016-12-16 17:05  蜗牛到牛  阅读(216)  评论(0编辑  收藏  举报