zoukankan      html  css  js  c++  java
  • Python通过多线程实现 `异步`

    import threading, time
    
    def thead(num):
        print("线程%s开始执行" % num)
        time.sleep(5)
        print("线程%s执行完毕" % num)
    
    def main():
        print("主方法开始执行")
        poll = []  # 线程池
        for i in range(1, 3):
            thead_one = threading.Thread(target=thead, args=(i,))
            poll.append(thead_one)  # 线程池添加线程
        for n in poll:
            n.start()  # 准备就绪,等待cpu执行
        print("主方法执行完毕")
        return
    
    print(time.ctime())
    num = main()
    print("返回结果为%s" % num)
    print(time.ctime())

    # 当代码执行到之后一行 print(time.ctime()), 方法 thead(num) 还在通过多线程的方式在运行,达到一种 `异步` 的效果
  • 相关阅读:
    第三天-基本数据类型 int bool str
    第二天-while循环 格式化输出 运算符 编码
    第一天-python基础
    Mysql
    Mysql
    Mysql
    Mysql
    Mysql
    Mysql
    Php
  • 原文地址:https://www.cnblogs.com/lab-zj/p/13152610.html
Copyright © 2011-2022 走看看