首页 > 编程语言 > 详细

【Rollo的Python之路】多线程实例

时间:2019-05-23 22:04:14      阅读:107      评论:0      收藏:0      [点我收藏+]

多线程实例:

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

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(ukill 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

 

【Rollo的Python之路】多线程实例

原文:https://www.cnblogs.com/rollost/p/10914684.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!