Python多线程

300 阅读1分钟
import threading
from time import sleep,ctime

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

if __name__ == '__main__':
    print('---开始---:%s'%ctime())
    t1 = threading.Thread(target=sing)
    t1.start()
    while True:
        length = len(threading.enumerate())
        print('当前运行的线程数为:%d'%length)
        if length<=1:
            break
        sleep(0.5)
        
        
        
打印结果
---开始---:Thu Oct 10 09:08:00 2019
正在唱歌...0
当前运行的线程数为:2
当前运行的线程数为:2
当前运行的线程数为:2
当前运行的线程数为:2
正在唱歌...1
当前运行的线程数为:2
当前运行的线程数为:2
当前运行的线程数为:2
当前运行的线程数为:2
正在唱歌...2
当前运行的线程数为:2
当前运行的线程数为:2
当前运行的线程数为:2
当前运行的线程数为:2
当前运行的线程数为:1