# -*- coding=utf8 -*- import threading from time import ctime, sleep #单线程实例 def frist(frist_name, length): for i in range(4): print('I was listening to %s %s'% (frist_name, ctime())) sleep(length) def second(second_name, length): for i in range(2): print('I was at the movie %s %s'% (second_name, ctime())) sleep(length) if __name__ == '__main__': frist('第一线程', 2) second('第二线程', 4) print('all over %s'% ctime()) </pre>
结果
1 2 3 4 5 6 7
I was listening to 第一线程 Tue Jan 17 23:13:07 2017 I was listening to 第一线程 Tue Jan 17 23:13:09 2017 I was listening to 第一线程 Tue Jan 17 23:13:11 2017 I was listening to 第一线程 Tue Jan 17 23:13:13 2017 I was at the movie 第二线程 Tue Jan 17 23:13:15 2017 I was at the movie 第二线程 Tue Jan 17 23:13:19 2017 all over Tue Jan 17 23:13:23 2017
# -*- coding=utf8 -*- import threading from time import ctime, sleep #多线程 def frist(frist_name, length): for i in range(4): print('I was listening to %s %s'% (frist_name, ctime())) sleep(length) def second(second_name, length): for i in range(2): print('I was at the second %s %s'% (second_name, ctime())) sleep(length) th1 = threading.Thread(target=frist, args=('第一线程', 1)) th2 = threading.Thread(target=second, args=('第二线程', 2)) threads = [th1,th2]
if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() t.join() print('all over %s' % ctime())</pre>
####结果
1 2 3 4 5 6 7
I was listening to 第一线程 Tue Jan 17 23:25:22 2017 I was at the second 第二线程 Tue Jan 17 23:25:22 2017 I was listening to 第一线程 Tue Jan 17 23:25:23 2017 I was listening to 第一线程 Tue Jan 17 23:25:24 2017 I was at the second 第二线程 Tue Jan 17 23:25:24 2017 I was listening to 第一线程 Tue Jan 17 23:25:25 2017 all over Tue Jan 17 23:25:26 2017