详细内容见代码注释↓
函数模式
import threading
from time import sleep
'''
函数模式
调用t=threading.Thread(target=函数名,[args=(变量1,变量2,..)])
线程直接调用目标函数
'''
def function(a1,a2,a3):
print a1,a2,a3
t1 = threading.Thread(target=function,args=(1,2,3))
t1.setDaemon(True) #阻塞模式,Ture父线程不等待子线程结束,
# False则父线程等待子线程结束,默认为False
t1.start() #启动线程
t1.join() #阻塞当前线程等待t1线程结束
类模式
'''
类模式
需要重写run()函数
'''
import threading
from time import sleep
lock = threading.Lock() #线程锁,可结合全局变量设置全局锁
class Th(threading.Thread): #继承threading.Thread类
def __init__(self,name):
threading.Thread.__init__(self) #先调用父类构造函数
self.name = name
def run(self): #重写run函数,线程默认从此执行
print '我是:',self.name
sleep(0.1)
lock.acquire() #申请线程锁,否则阻塞
print self.name,'完成' #加锁执行
lock.release() #释放线程锁
if __name__ == '__main__':
for i in range(0,3): #执行3个线程并行执行
t = Th('线程'+str(i))
# t.setDaemon(True)
t.start()