Python 多线程的三种创建方式

来源:互联网 发布:手机淘宝补差价 编辑:程序博客网 时间:2024/05/22 17:59

第一种方式:(不考虑冲突,线程通信)

import win32api  #引用系统函数import _thread #多线程def  show():    win32api.MessageBox(0, "你的账户很危险", "来自支付宝的问候", 6)for  i  in range(5):    _thread.start_new_thread(show,())  #()元组,用于传递参数  函数实现多线程while True:  #阻塞主线程,主线程执行结束后,其子线程会同时被杀死    pass

第二种方式:(不考虑冲突,线程通信)

import threadingimport win32api  #引用系统函数 def  show(i):    win32api.MessageBox(0, "你的账户很危险"+str(i), "来自支付宝的问候", 6)#target=show线程函数   ,args=()参数   类的构造实现多线程threading.Thread(target=show,args=(1,)).start()threading.Thread(target=show,args=(2,)).start()threading.Thread(target=show,args=(3,)).start()

第三种方式:(类线程,常用的方式)
import threadingimport timeimport win32api  #引用系统函数class Mythread(threading.Thread): #继承threading.Thread 实现多线程    def __init__(self,num):      #可以通过自定义线程类的构造函数传递参数        threading.Thread.__init__(self)          self.num=num    def run(self): #run重写,        win32api.MessageBox(0, "你的账户很危险"+str(self.num), "来自支付宝的问候", 6)mythread=[]   #集合listfor  i  in range(5):    t=Mythread(i)  #初始化    t.start()    mythread.append(t) #加入线程集合for mythd  in mythread:  #mythd是一个线程    mythd.join()   #主线程(for循环)等待子线程mythd执行完成后,再执行。在join之前就都已经start这些线程,所以这些线程是乱序(并发)执行的print("game over")