您的位置:首页 > 编程语言 > Python开发

Python 多线程的三种创建方式

2017-10-13 17:17 309 查看
第一种方式:(不考虑冲突,线程通信)

import win32api  #引用系统函数
import _thread #多线程

def  show():
win32api.MessageBox(0, "你的账户很危险", "来自支付宝的问候", 6)

for  i  in range(5):
_thread.start_new_thread(show,())  #()元组,用于传递参数  函数实现多线程

while True:  #阻塞主线程,主线程执行结束后,其子线程会同时被杀死
pass

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

import threading
import 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 threading
import time
import 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=[]   #集合list
for  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")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python