zoukankan      html  css  js  c++  java
  • Python的多线程

    线程间的关系

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    import threading
    import time
    
    def MyThread(n):
        print("Running Thread",n)
        print(threading.current_thread()) #打印当前线程的类型
        time.sleep(2)
    
    for i in range(20):
        t = threading.Thread(target=MyThread,args=(i,))
        t.start()
    
    print("Running Main Threading",threading.current_thread())
    print(threading.active_count()) #计算线程数
    

     运行结果

    主线程和子线程同时执行,然后脚本执行Mythread函数里的time.sleep(2),运行停顿大概2秒

    线程数为当前主线程和子线程数之和

    def MyThread(n):
        print("Running Thread",n)
        print(threading.current_thread())
        time.sleep(2)
    
    for i in range(20):
        t = threading.Thread(target=MyThread,args=(i,))
        t.start()
    

     这段代码为主线程启动的子线程

    print("Running Main Threading",threading.current_thread())
    print(threading.active_count())
    

     这段代码为主线程执行的线程

    多线程的等待

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    import threading
    import time
    
    All_Thread = []
    
    def MyThread(n):
        print("Running %s Thread"%n)
        time.sleep(2)
    
    for i in range(20):
        t = threading.Thread(target=MyThread,args=(i,))
        t.start()
    
    print("Finished All Sub-thread")
    

     运行,查看结果

    该脚本同时执行主线程和子线程

    如果想先执行完子线程再执行主线程,可以使用join()

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    import threading
    import time
    
    All_Thread = []
    
    def MyThread(n):
        print("Running %s Thread"%n)
        time.sleep(2)
    
    for i in range(20):
        t = threading.Thread(target=MyThread,args=(i,))
        t.start()
        All_Thread.append(t)
    
    for t in All_Thread:
        t.join()
    
    print("Finished All Sub-thread")
    

     运行,查看结果

    先执行了子线程,然后停留了大概2秒,再执行了主线程

    线程号

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    import threading
    
    def MyThread():
        print(threading.get_ident())
    
    for i in range(10):
        t = threading.Thread(target=MyThread)
        t.start()
    

     运行结果

    打印出了这10个子线程的id号

  • 相关阅读:
    2003系统IIS上传文件不能超过200K的解决方案
    ASP从编辑框中获取图片路径
    ASP 编码转换大全 UTF8、GB2312、二进制、十进制代码、十六进制
    解决IE6、IE7、IE8样式不兼容问题
    py2exe setup.py
    Python to 2bit
    python访问ACCESS
    Pamie Web自动化
    Perl 笔记
    常用工具全盗版 汗颜了
  • 原文地址:https://www.cnblogs.com/sch01ar/p/8030198.html
Copyright © 2011-2022 走看看