简单的来说明一下多线程,python多线程的支持并不友好,因为全局GIL锁(全局安全锁)的原因,只能单核使用,且每次只能运行一个线程,更多是用在IO操作上。
线程创建的两种方法
import threading,time#倒入线程模块 def func(name): time.sleep(1) print("hello %s" %name) if __name__=="__main__" : t=threading.Thread(target=func,args=("alex",)) t.start() print("main ending")
#继承threading.Thread类,并重写run方法 import threading,time class Thre(threading.Thread): #def __init__(xxx):如果有参数的话,要继承父类的init方法 #super().__init__() def run(): time.sleep(1) print("hello") if __name__=="__main__":#注意使用模块的时候一定要把调用方法,放在main下 t1=Threa() t2=Threa() t1.start() t2.start() print("main ending")
线程常用的几个方法:join,setDaemo,getname
# import threading # import time #join方法:只有当子线程执行完毕过后,在继续执行主线程 # # def music(): # print("begin to listen %s"%time.ctime()) # time.sleep(3) # print("stop to listen %s"%time.ctime()) # # # # # def game(): # print("begin to play game %s"%time.ctime()) # time.sleep(5) # print("stop to play game %s"%time.ctime()) # # # # # if __name__=="__main__": # p1=threading.Thread(target=music) # p2=threading.Thread(target=game) # p1.start() # p2.start() # # p2.join()#join等待线程的结束 # p1.join() # print("ending")#主线程 # #
import time import threading def Listenmusic(): print("begin to music %s"%time.ctime()) time.sleep(3) print("ending to music") def RecordBlog(): print("writen to blog") time.sleep(5) print("ending to blog") threads=[] t1=threading.Thread(target=Listenmusic) t2=threading.Thread(target=RecordBlog) threads.append(t1) threads.append(t2) if __name__=="__main__": t1.setDaemon(True)#守护线程,主线程一结束便不会执行 for t in threads: #t.setDaemon(True) #守护线程 一定在start之前设置 t.start() # print(t.getName())返回线程的名字 Thread-1 print("count",threading.active_count())#判断当前程序有多少个线程在运行 #t.join()#串行 #t.join()--->循环的最后一个参数-->t2.join if threading.active_count()==1: print("主线程allover %s"%time.ctime())