Python多线程

来源:互联网 发布:java中日志的使用 编辑:程序博客网 时间:2024/05/22 05:23

详细内容见代码注释↓

函数模式

import threadingfrom time import sleep'''函数模式调用t=threading.Thread(target=函数名,[args=(变量1,变量2,..)])线程直接调用目标函数'''def function(a1,a2,a3):    print a1,a2,a3t1 = threading.Thread(target=function,args=(1,2,3))t1.setDaemon(True)  #阻塞模式,Ture父线程不等待子线程结束,                    # False则父线程等待子线程结束,默认为Falset1.start()          #启动线程t1.join()           #阻塞当前线程等待t1线程结束

类模式

'''类模式需要重写run()函数'''import threadingfrom time import sleeplock = 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()