一般来说,python使用线程有两种模式:
(1)创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;
(1)创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;
(2)继承Thread类,创建一个新的class,将要执行的代码 写到run函数里面。
(1)方法:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import threading,time
def test(loop, sec):
print 'start loop', loop, 'at:', time.ctime()
time.sleep(sec)
print 'loop', loop, 'done at:', time.ctime()
def main():
print 'starting at:', time.ctime()
for i in xrange(10):
th = threading.Thread(target= test,args= (i,2))
th.start()
th.join()
print 'all Done at:', time.ctime()
if __name__ == '__main__':
main()
结果:
starting at: Tue May 2 14:01:49 2017
start loop 0 at: Tue May 2 14:01:49 2017
loop 0 done at: Tue May 2 14:01:51 2017
start loop 1 at: Tue May 2 14:01:51 2017
loop 1 done at: Tue May 2 14:01:53 2017
start loop 2 at: Tue May 2 14:01:53 2017
loop 2 done at: Tue May 2 14:01:55 2017
start loop 3 at: Tue May 2 14:01:55 2017
loop 3 done at: Tue May 2 14:01:57 2017
start loop 4 at: Tue May 2 14:01:57 2017
loop 4 done at: Tue May 2 14:01:59 2017
start loop 5 at: Tue May 2 14:01:59 2017
loop 5 done at: Tue May 2 14:02:01 2017
start loop 6 at: Tue May 2 14:02:01 2017
loop 6 done at: Tue May 2 14:02:03 2017
start loop 7 at: Tue May 2 14:02:03 2017
loop 7 done at: Tue May 2 14:02:05 2017
start loop 8 at: Tue May 2 14:02:05 2017
loop 8 done at: Tue May 2 14:02:07 2017
start loop 9 at: Tue May 2 14:02:07 2017
loop 9 done at: Tue May 2 14:02:09 2017
all Done at: Tue May 2 14:02:09 2017
(2)方法
#!/usr/bin/python
# -*- coding: utf-8 -*-
import threading,time
class myThread (threading.Thread) :
def __init__(self, loop, sec) :
super(myThread, self).__init__()
self.loop = loop
self.sec = sec
def run(self):
print 'start loop', self.loop, 'at:', time.ctime()
time.sleep(self.sec)
print 'loop', self.loop, 'done at:', time.ctime()
def main():
print 'starting at:', time.ctime()
for i in xrange(10):
th = myThread(i,2)
th.start()
th.join()
print 'all Done at:', time.ctime()
if __name__ == '__main__':
main()
结果:
starting at: Tue May 2 14:13:17 2017
start loop 0 at: Tue May 2 14:13:17 2017
loop 0 done at: Tue May 2 14:13:19 2017
start loop 1 at: Tue May 2 14:13:19 2017
loop 1 done at: Tue May 2 14:13:21 2017
start loop 2 at: Tue May 2 14:13:21 2017
loop 2 done at: Tue May 2 14:13:23 2017
start loop 3 at: Tue May 2 14:13:23 2017
loop 3 done at: Tue May 2 14:13:25 2017
start loop 4 at: Tue May 2 14:13:25 2017
loop 4 done at: Tue May 2 14:13:27 2017
start loop 5 at: Tue May 2 14:13:27 2017
loop 5 done at: Tue May 2 14:13:29 2017
start loop 6 at: Tue May 2 14:13:29 2017
loop 6 done at: Tue May 2 14:13:31 2017
start loop 7 at: Tue May 2 14:13:31 2017
loop 7 done at: Tue May 2 14:13:33 2017
start loop 8 at: Tue May 2 14:13:33 2017
loop 8 done at: Tue May 2 14:13:35 2017
start loop 9 at: Tue May 2 14:13:35 2017
loop 9 done at: Tue May 2 14:13:37 2017
all Done at: Tue May 2 14:13:37 2017