标签:线程并发 包装 time() alt enumerate rom 作用 main 你好
import threading import time def hello_for(): print("你好 世界, 你好 中国") time.sleep(1) if __name__ == "__main__": for i in range(5): t = threading.Thread(target=hello_for) t.start() #启动线程,即让线程开始执行
运行结果:
import threading import time def hello_for(): print("你好 世界, 你好 中国") time.sleep(1) if __name__ == "__main__": for i in range(5): t = threading.Thread(target=hello_for) t.start() #启动线程,即让线程开始执行
运行结果:
start()
时,才会真正的创建线程,并且开始执行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() print(‘---结束---:%s‘%ctime())
运行结果:
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)
运行结果:
标签:线程并发 包装 time() alt enumerate rom 作用 main 你好
原文地址:https://www.cnblogs.com/aydenwang/p/9427862.html