<span>2019-02-02 Python学习之多线程</span>

1.主线程和次线程

若主线程结束则次线程也会结束
如何避免主线程先结束:
结尾处加上

while True:
	pass

e.g.

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


def show(i):
    win32api.MessageBox(0, "Hello", "Me", 0)

for i in range(4):
    _thread.start_new_thread(show,(i,))#把函数当作参数传递,()元组,用于传递参数

while True:
    pass

但是这样的操作无法终止程序

threading模块,基于类实现多线程

import threading
import win32api


class Mythread(threading.Thread):
    def run(self):  #run重写
        win32api.MessageBox(0,"Hello","Me",0)


for i in range(5):
    t = Mythread()  #初始化
    t.start()       #开启

while True:
    pass

将最后while True替换为join方法:

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


def show():
    win32api.MessageBox(0, "你的账户很危险", "from Alipay", 0)

list=[]
for i in range(4):
    t = threading.Thread(target=show)
    t.start()#把函数当作参数传递,()元组,用于传递参数
    list.append(t)

for i in list:
	i.join()

类线程的两种风格

import threading
import time
import win32api


class Mythread(threading.Thread):   #继承threading.Thread
    def run(self):  #run重写
        win32api.MessageBox(0,"Hello","max",0)


""" for i in range(5): t = Mythread() #初始化 t.start() #开启 t.join() #主线程等待线程t执行完成,顺序风格 """
mythread = [] #集合list
for i in range(5):
    t = Mythread()
    t.start()
    mythread.append(t)  #加入线程集合

for mythd in mythread:  #mythd是一个线程
    mythd.join()    #主线程等待线程t执行完成,不需要阻塞

print("gameover")

尹成python视频 学习
呀哈哈

全部评论

相关推荐

09-01 09:00
已编辑
四川旅游学院 运营
牛客55195891...:主要是专业不好,别的没毛病
牛客解忧铺
点赞 评论 收藏
分享
08-27 21:03
已编辑
成都理工大学 Java
冷花幽露:大概率是了,京东面试就是这样。我上周一面也是20多分钟,面试官问的很刁钻的问题也答上来了,面完过了几天还是没推进,泡池子,昨天一看挂了。如果一面完第2天没有收到2面邀请,基本上不用抱希望了。如果你的bg是985,面试流程也是和我们一样,20多分钟,唯一区别就是面完他们会很快收到二面邮件,而不像我们泡池子然后挂掉
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务