【详解】Python多线程的实现

多线程的意思是:同时运行多个线程,通俗的说,就是同时干多件事情。

我们之前写过好多Python程序,定义了很多的方法,主方法main()中的各个函数都是按顺序进行的。

多线程要做的,就是让这些函数同时运行!

下面举例进行说明。

单线程:

#coding=utf-8

import sys
import datetime

from time import ctime,sleep

def music(func):
    for i in range(2):
        print "I was listening to %s. %s" %(func,ctime())
        sleep(1)

def move(func):
    for i in range(2):
        print "I was at the %s! %s" %(func,ctime())
        sleep(5)



if __name__ == '__main__':
    print "===%s start===%s"%(sys.argv[0], datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S"))
    music(u'爱情买卖')
    move(u'阿凡达')
    print "all over %s" %ctime()
    print "===%s start===%s"%(sys.argv[0], datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S"))

表示先听音乐后看电影,听音乐时长一秒,听两遍,看电影时长5秒,看两遍

运行结果如下:

===C:/Users/Administrator/PycharmProjects/planBilibili/thread1.py start===2015-12-10 17:05:52
I was listening to 爱情买卖. Thu Dec 10 17:05:52 2015
I was listening to 爱情买卖. Thu Dec 10 17:05:53 2015
I was at the 阿凡达! Thu Dec 10 17:05:54 2015
I was at the 阿凡达! Thu Dec 10 17:05:59 2015
all over Thu Dec 10 17:06:04 2015
===C:/Users/Administrator/PycharmProjects/planBilibili/thread1.py start===2015-12-10 17:06:04
我们看到,的确是顺序进行的,听一遍后再听一遍。看一遍后再看一遍,所以运行时间是12秒。


多线程呢,是看电影的同时也听音乐,如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import threading
from time import ctime,sleep
import sys
import datetime


def music(func):
    for i in range(2):
        print "I was listening to %s. %s" %(func,ctime())
        sleep(1)

def move(func):
    for i in range(2):
        print "I was at the %s! %s" %(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__':
    print "===%s start===%s"%(sys.argv[0], datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S"))
    for t in threads:
        t.setDaemon(True)
        t.start()
    t.join()
    print "all over %s" %ctime()
    print "===%s start===%s"%(sys.argv[0], datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S"))
多线程的实现,首先导入threading模块

import threading
然后创建线程数组并把方法加入线程

threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2)

主方法中运行线程。

for t in threads:
        t.setDaemon(True)
        t.start()
 t.join()
【注意】一定要加t.join()

  这个函数表示threads线程运行结束后,才能进入主线程,

  这里的主线程,指的是

  print "all over %s" %ctime()
  print "===%s start===%s"%(sys.argv[0], datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S"))

该脚本运行效果如下:

===C:/Users/Administrator/PycharmProjects/planBilibili/thread2.py start===2015-12-10 17:13:56
I was listening to 爱情买卖. Thu Dec 10 17:13:56 2015
I was at the 阿凡达! Thu Dec 10 17:13:56 2015
I was listening to 爱情买卖. Thu Dec 10 17:13:57 2015
I was at the 阿凡达! Thu Dec 10 17:14:01 2015
all over Thu Dec 10 17:14:06 2015
===C:/Users/Administrator/PycharmProjects/planBilibili/thread2.py start===2015-12-10 17:14:06
运行时间10秒。可以看到,听音乐和看电影,是同时进行的!

多个事情同时进行,多线程的意义就在于此!


你可能感兴趣的:(python,27,Python多线程)