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
  • 相关阅读:
    CSS3自定义滚动条样式 -webkit-scrollbar
    仿flash的文字动画效果
    使用PowerDesigner导出MySQL数据库建模
    将博客搬至CSDN
    centos6.3安装MySQL 5.6(转)
    # mysql -u root -p -bash: mysql: command not found
    win8设置保护眼睛的颜色
    网关末尾要么是1要么是254
    虚机centos和本机Windows之间文件的拷贝无法用xftp时用FileZilla也行
    Java基础知识总结之基础数据类型
  • 原文地址:https://www.cnblogs.com/rollost/p/10914684.html
Copyright © 2011-2022 走看看