多任务03-线程

线程

python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的,可以更加方便的被使用

1. 使用threading模块

单线程执行

#coding=utf-8
import time

def saySorry():
    print("亲爱的,我错了,我能吃饭了吗?")
    time.sleep(1)

if __name__ == "__main__":
    for i in range(5):
        saySorry()

终端命令: python + 文件名

运行结果:

亲爱的,我错了,我能吃饭了吗?

亲爱的,我错了,我能吃饭了吗?

亲爱的,我错了,我能吃饭了吗?

亲爱的,我错了,我能吃饭了吗?

亲爱的,我错了,我能吃饭了吗?

多线程执行

#coding=utf-8
import threading
import time

def saySorry():
    print("亲爱的,我错了,我能吃饭了吗?")
    time.sleep(1)

if __name__ == "__main__":
    for i in range(5):
        t = threading.Thread(target=saySorry)
        t.start() #启动线程,即让线程开始执行

终端命令: python + 文件名

运行结果:

亲爱的,我错了,我能吃饭了吗?

亲爱的,我错了,我能吃饭了吗?

亲爱的,我错了,我能吃饭了吗?

亲爱的,我错了,我能吃饭了吗?

亲爱的,我错了,我能吃饭了吗?

说明

  1. 可以明显看出使用了多线程并发的操作,花费时间要短很多
  2. 当调用start()时,才会真正的创建线程,并且开始执行

2. 主线程会等待所有的子线程结束后才结束

#coding=utf-8
import threading
from time import sleep,ctime

def sing():
    for i in range(3):
        print("正在唱歌...%d"%i)
        sleep(1)

def dance():
    for i in range(3):
        print("正在跳舞...%d"%i)
        sleep(1)

if __name__ == '__main__':
    print('---开始---:%s'%ctime())

    t1 = threading.Thread(target=sing)
    t2 = threading.Thread(target=dance)

    t1.start()
    t2.start()

    #sleep(5) # 屏蔽此行代码,试试看,程序是否会立马结束?
    print('---结束---:%s'%ctime())

终端命令: python + 文件名

运行结果:

---开始---

正在唱歌...0

---结束---

正在跳舞...0

正在唱歌...1

正在跳舞...1

正在唱歌...2

正在跳舞...2

3. 查看线程数量

#coding=utf-8
import threading
from time import sleep,ctime

def sing():
    for i in range(3):
        print("正在唱歌...%d"%i)
        sleep(1)

def dance():
    for i in range(3):
        print("正在跳舞...%d"%i)
        sleep(1)

if __name__ == '__main__':
    print('---开始---:%s'%ctime())

    t1 = threading.Thread(target=sing)
    t2 = threading.Thread(target=dance)

    t1.start()
    t2.start()

    while True:
        length = len(threading.enumerate())
        print('当前运行的线程数为:%d'%length)
        if length<=1:
            break

        sleep(0.5)

终端命令: python + 文件名

运行结果:

正在唱歌...0

当前运行的线程数为:3

正在跳舞...0

当前运行的线程数为:3

当前运行的线程数为:3

正在唱歌...1

正在跳舞...1

当前运行的线程数为:3

当前运行的线程数为:3

正在唱歌...2

正在跳舞...2

当前运行的线程数为:3

当前运行的线程数为:1

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值