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

  • 相关阅读:
    (转)一次棘手的rootvg更换硬盘处理过程
    mysql:服务器错误代码
    (转)运行跟踪格式化程序
    (转)InnoDB存储引擎MVCC实现原理
    (转)漫谈JVM
    (转)mysql、innodb和加锁分析
    (转)DB2和 Oracle的并发控制(锁)比较
    (转)Mysql主从复制搭建及详解
    BigDecimal 、BigInteger
    Date、DateFormat、SimpleDateFormat、Calendar
  • 原文地址:https://www.cnblogs.com/roccoshi/p/13027103.html
Copyright © 2011-2022 走看看