zoukankan      html  css  js  c++  java
  • 【Rollo的Python之路】多线程实例

    多线程实例:

    共节省两秒时间,以最大的时间为准,小的时间就是省下来的时间。

    IO密集型项目,多线程可以节省时间,像爬虫这样的项目

    计算密集型项目,就是用C来代替python写。

    或者可以是协和+多进程。

    import threading
    import time
    from time import ctime,sleep
    
    def music(func):
        for i in range(2):
            print("I was listening to %s.%s" %(func,ctime()))
            sleep(1)
            print("end listening %s" % ctime())
    
    def movie(func):
        for i in range(2):
            print("I was at the %s %s" %(func,ctime()))
            sleep(5)
            print("end watch %s" % ctime())
    
    threads = []
    
    t1 = threading.Thread(target=music,args=("overstock",))
    threads.append(t1)
    t2 = threading.Thread(target=movie,args=("kill them all",))
    threads.append(t2)
    
    if __name__ =="__main__":
        for t in threads:
            t.start()
            print("all over %s" %ctime())
    
    
    执行结果:
    
    
    I was at the kill them all Thu May 23 21:26:14 2019
    all over Thu May 23 21:26:14 2019
    end listening Thu May 23 21:26:15 2019
    I was listening to overstock.Thu May 23 21:26:15 2019
    end listening Thu May 23 21:26:16 2019
    end watch Thu May 23 21:26:19 2019
    I was at the kill them all Thu May 23 21:26:19 2019
    end watch Thu May 23 21:26:24 2019

    单线程实例:

    import time
    from time import ctime,sleep
    
    
    def music(func):
        for i in range(2):
            print("I was listening to %s.%s" %(func,ctime()))
            sleep(1)
    
    def movie(func):
        for i in range(2):
            print("I was at the %s %s" %(func,ctime()))
            sleep(5)
    
    
    if __name__ =="__main__":
        music(u'七里香')
        movie(u'kill them all')
    
    执行结果:
    #注意时间间隔
    
    I was listening to 七里香.Thu May 23 21:31:12 2019
    I was listening to 七里香.Thu May 23 21:31:13 2019
    I was at the kill them all Thu May 23 21:31:14 2019
    I was at the kill them all Thu May 23 21:31:19 2019
  • 相关阅读:
    一个完整的SQL SERVER数据库全文索引的示例
    sqlhelper for access
    解决打开网站弹出下载文件
    18句话入门SQLServer XML
    c# winform 自动关闭messagebox 模拟回车
    jquery json
    用超级巡警批量清除被挂马的网页
    sqlhelper for sql
    SQL XML DML 数据修改
    post方法易错地方
  • 原文地址:https://www.cnblogs.com/rollost/p/10914684.html
Copyright © 2011-2022 走看看