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

  • 相关阅读:
    LeetCode-167-两数之和 II
    LeetCode-160-相交链表
    LeetCode-155-最小栈
    [leetcode]7. Reverse Integer反转整数
    [leetcode]4. Median of Two Sorted Arrays俩有序数组的中位数
    [leetcode]2. Add Two Numbers两数相加
    [leetcode]210. Course Schedule II课程表II
    Topological Sorting拓扑排序
    [leetcode]62. Unique Paths 不同路径(求路径和)
    [leetcode]387. First Unique Character in a String第一个不重复字母
  • 原文地址:https://www.cnblogs.com/roccoshi/p/13027103.html
Copyright © 2011-2022 走看看