单线程
整个程序只有一个执行流,所有的任务只能依次顺序执行。
举例:假设在单线程环境下,有走路和唱歌两个任务,那么这两个任务只能顺序执行了哦。(也就是只能先走路,然后再唱歌,听起来是不是很变扭)
# coding:gbk
from time import ctime,sleep
def walk():
print 'I was walking. %s' % ctime()
sleep(1)
def sing():
print 'I was singing. %s' % ctime()
sleep(3)
if __name__ == '__main__':
walk()
sing()
print 'all over. %s' % ctime()
执行结果:
C:\Python27\python.exe E:/pythonproj/基础练习/t1.py
I was walking. Mon Oct 22 16:40:55 2018
I was singing. Mon Oct 22 16:40:56 2018
all over. Mon Oct 22 16:40:59 2018
Process finished with exit code 0
多线程
程序中存在多个执行流,每个执行流独立执行自己的任务,提高了整个程序的执行效率。
举例:在多线程环境下,如果有走路和唱歌两个任务,那么这两个任务就可以并行执行了。
# coding:gbk
from time import ctime,sleep
import threading
def walk():
print 'I was walking. %s' % ctime()
sleep(1)
def sing():
print 'I was singing. %s' % ctime()
sleep(3)
if __name__ == '__main__':
threads=[]
threads.append(threading.Thread(target=walk,args=())) //创建线程对象,并追加到threads列表中
threads.append(threading.Thread(target=sing,args=())) //创建线程对象,并追加到threads列表中
for i in range(len(threads)):
threads[i].start() //开始线程活动
for i in range(len(threads)):
threads[i].join() //主线程阻塞等待子线程结束
print 'all over. %s' % ctime()
执行结果:
C:\Python27\python.exe E:/pythonproj/基础练习/t1.py
I was walking. Mon Oct 22 17:03:06 2018
I was singing. Mon Oct 22 17:03:06 2018
all over. Mon Oct 22 17:03:09 2018
Process finished with exit code 0