创建多线程常用的三种方法:

  • 创建Thread的实例,传给它一个函数
  • 创建Thread的实例,传给它一个可调用的类实例(不推荐)
  • 派生Thread的子类,并创建子类的实例(推荐)

创建Thread的实例,传给它一个函数

 #!/usr/bin/env python
# coding:utf-8 import threading
from time import ctime, sleep loops = [4, 2] def loop(n, sec):
print 'start loop', n, ' at: ', ctime()
sleep(sec)
print 'loop', n, ' done at: ', ctime() def main():
print 'starting at: ', ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = threading.Thread(target=loop, args=(i, loops[i]))
threads.append(t) for i in nloops: # start threads
threads[i].start() for i in nloops: # wait for all threads to finish
threads[i].join() print 'all DONE at: ', ctime() if __name__ == '__main__':
main()

执行结果:

liuqian@ubuntu:~$ python test_threading1.py
starting at:  Wed Jul 20 13:20:06 2016
start loop 0  at:  Wed Jul 20 13:20:06 2016
start loop 1  at:  Wed Jul 20 13:20:06 2016
loop 1  done at:  Wed Jul 20 13:20:08 2016
loop 0  done at:  Wed Jul 20 13:20:10 2016
all DONE at:  Wed Jul 20 13:20:10 2016

【说明】

join([timeout])方法将等待线程结束,或者在提供了超时时间的情况下达到超时时间。对于join()方法而言,其实它根本不需要调用。一旦线程启动,它就会一直执行,直到给定的函数完成后退出。如果主线程还有其他事情要去做,而不是等待这些线程完成(例如其他处理或者等待新的客户端请求),就可以不调用join()。join()只在你需要等待线程完成的时候才是有用的。

创建Thread的实例,传给它一个可调用的类实例

 #!/usr/bin/env python
# coding:utf-8 import threading
from time import ctime, sleep loops = [4,2] class ThreadFunc(object): def __init__(self, func, args, name=''):
self.name = name
self.func = func
self.args = args def __call__(self):
self.func(*self.args) def loop(n, sec):
print 'start loop', n, ' at: ', ctime()
sleep(sec)
print 'loop', n, ' done at: ', ctime() def main():
print 'starting at: ', ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = threading.Thread(target=ThreadFunc(loop, (i, loops[i]), loop.__name__))
threads.append(t) for i in nloops: # start threads
threads[i].start() for i in nloops: # wait for all threads to finish
threads[i].join() print 'all DONE at: ', ctime() if __name__ == '__main__':
main()

输出与第一个案例一样。

【说明】当创建新线程时,Thread类的代码将调用ThreadFunc对象,此时会调用__cal__()这个特殊方法。

派生Thread的子类,并创建子类的实例(推荐)

 #!/usr/bin/env python
# coding:utf-8 import threading
from time import ctime, sleep loops = [4,2] class MyThread(threading.Thread): def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args def run(self): # 必须要写
self.func(*self.args) def loop(n, sec):
print 'start loop', n, ' at: ', ctime()
sleep(sec)
print 'loop', n, ' done at: ', ctime() def main():
print 'starting at: ', ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = MyThread(loop, (i, loops[i]), loop.__name__)
threads.append(t) for i in nloops: # start threads
threads[i].start() for i in nloops: # wait for all threads to finish
threads[i].join() print 'all DONE at: ', ctime() if __name__ == '__main__':
main()
05-11 08:21