Python 多线程的实例详解
一)线程基础
1、创建线程:
thread模块提供了start_new_thread函数,用以创建线程。start_new_thread函数成功创建后还可以对其进行操作。
其函数原型:
start_new_thread(function,atgs[,kwargs])
其参数含义如下:
function: 在线程中执行的函数名
args:元组形式的参数列表。
kwargs: 可选参数,以字典的形式指定参数
方法一:通过使用thread模块中的函数创建新线程。
>>> import thread >>> def run(n): for i in range(n): print i >>> thread.start_new_thread(run,(4,)) #注意第二个参数一定要是元组的形式 53840 1 >>> 2 3 KeyboardInterrupt >>> thread.start_new_thread(run,(2,)) 17840 1 >>> thread.start_new_thread(run,(),{'n':4}) 39720 1 >>> 2 3 thread.start_new_thread(run,(),{'n':3}) 32480 1 >>> 2
方法二:通过继承threading.Thread创建线程
>>> import threading >>> class mythread(threading.Thread): def __init__(self,num): threading.Thread.__init__(self) self.num = num def run(self): #重载run方法 print 'I am', self.num >>> t1 = mythread(1) >>> t2 = mythread(2) >>> t3 = mythread(3) >>> t1.start() #运行线程t1 I am >>> 1 t2.start() I am >>> 2 t3.start() I am >>> 3
方法三:使用threading.Thread直接在线程中运行函数。
import threading >>> def run(x,y): for i in range(x,y): print i >>> t1 = threading.Thread(target=run,args=(15,20)) #直接使用Thread附加函数args为函数参数 >>> t1.start() 15 >>> 16 17 18 19
二)Thread对象中的常用方法:
1、isAlive方法:
>>> import threading >>> import time >>> class mythread(threading.Thread): def __init__(self,id): threading.Thread.__init__(self) self.id = id def run(self): time.sleep(5) #休眠5秒 print self.id >>> t = mythread(1) >>> def func(): t.start() print t.isAlive() #打印线程状态 >>> func() True >>> 1
2、join方法:
原型:join([timeout])
timeout: 可选参数,线程运行的最长时间
import threading >>> import time #导入time模块 >>> class Mythread(threading.Thread): def __init__(self,id): threading.Thread.__init__(self) self.id = id def run(self): x = 0 time.sleep(20) print self.id >>> def func(): t.start() for i in range(5): print i >>> t = Mythread(2) >>> func() 0 1 2 3 4 >>> 2 def func(): t.start() t.join() for i in range(5): print i >>> t = Mythread(3) >>> func() 3 0 1 2 3 4 >>>
新闻热点
疑难解答