【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

 

转载于:https://www.cnblogs.com/rollost/p/10914684.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值