刚开始时候,cpu不支持多任务,所以是顺序执行的,比如先听歌,再看电影
from time import ctime,sleep def music(): for i in range(2): print("I was listening to music. %s",ctime()) sleep(1) def move(): for i in range(2): print("I was at the movies! %s",str(ctime())) sleep(5) if __name__ == '__main__': music() move() print("all over %s" %ctime())
后来,cpu支持了多任务,那我们就可以一边听歌,一边看电影了,两个程序同时是运行状态的。下面的例子是非阻塞的。
#coding=utf-8 import threading from time import ctime,sleep def music(func): for i in range(2): print("I was listening to {0}. {1}" .format(func,ctime())) sleep(1) def move(func): for i in range(2): print ("I was at the {0}! {1}".format(func,ctime())) sleep(5) threads = [] t1 = threading.Thread(target=music,args=(u'爱情买卖',)) threads.append(t1) t2 = threading.Thread(target=move,args=(u'阿凡达',)) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(False) t.start() print("all over %s" %ctime())
输出
I was listening to 爱情买卖. Fri Jan 18 14:36:20 2019 I was at the 阿凡达! Fri Jan 18 14:36:20 2019 all over Fri Jan 18 14:36:20 2019 I was listening to 爱情买卖. Fri Jan 18 14:36:21 2019 I was at the 阿凡达! Fri Jan 18 14:36:25 2019 [Program finished]
阻塞模式,由于主线程执行完毕,子线程不再继续执行
#coding=utf-8 import threading from time import ctime,sleep def music(func): for i in range(2): print("I was listening to {0}. {1}" .format(func,ctime())) sleep(1) def move(func): for i in range(2): print ("I was at the {0}! {1}".format(func,ctime())) sleep(5) threads = [] t1 = threading.Thread(target=music,args=(u'爱情买卖',)) threads.append(t1) t2 = threading.Thread(target=move,args=(u'阿凡达',)) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() print("all over %s" %ctime())
输出
I was listening to 爱情买卖. Fri Jan 18 14:38:36 2019 I was at the 阿凡达! Fri Jan 18 14:38:36 2019 all over Fri Jan 18 14:38:36 2019 [Program finished]
我们只对上面的程序加了个join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。
注意: join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。
#coding=utf-8 import threading from time import ctime,sleep def music(func): for i in range(2): print("I was listening to {0}. {1}" .format(func,ctime())) sleep(1) def move(func): for i in range(2): print ("I was at the {0}! {1}".format(func,ctime())) sleep(5) threads = [] t1 = threading.Thread(target=music,args=(u'爱情买卖',)) threads.append(t1) t2 = threading.Thread(target=move,args=(u'阿凡达',)) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() t.join() print("all over %s" %ctime())
输出
I was listening to 爱情买卖. Fri Jan 18 14:47:26 2019 I was at the 阿凡达! Fri Jan 18 14:47:26 2019 I was listening to 爱情买卖. Fri Jan 18 14:47:27 2019 I was at the 阿凡达! Fri Jan 18 14:47:31 2019 all over Fri Jan 18 14:47:36 2019 [Program finished]