zoukankan      html  css  js  c++  java
  • 2019-02-02 Python学习之多线程

    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视频 学习
    呀哈哈

  • 相关阅读:
    函数
    函数式编程
    高级特性
    内建的数据结构
    条件语句和循环语句
    java_基础——用代码编译.java文件+加载class文件
    日期格式私人定制——SimpleDateFormat
    java7(3)——增强的catch之自动释放资源
    java7(2)——使用mutilcatch注意事项
    java7(1)——反编译深入理解增强的switch(读字节命令实战)
  • 原文地址:https://www.cnblogs.com/roccoshi/p/13027103.html
Copyright © 2011-2022 走看看