赞
踩
函数原型:
threading.Thread(target, name, args, kwargs)
参数:
举例:
import threading import time def func_a(name_a): for i in range(5): print("我是"+name_a) time.sleep(1) def func_b(name_b): for i in range(5): print("我是"+name_b) time.sleep(1) if __name__ == '__main__': # 创建两个子线程 t1 = threading.Thread(target=func_a, args=('Tom',)) t2 = threading.Thread(target=func_b, args=('Alex',)) # 启动子线程 t1.start() t2.start() # 输出为: # 我是Tom # 我是Alex # 我是Tom # 我是Alex # 我是Tom我是Alex # # 我是Alex # 我是Tom # 我是Alex # 我是Tom
再来个例子:
import threading import time def demo_a(): # 获取线程名 t = threading.current_thread() print(t) for i in range(5): print(i, "---dome_a---", t.name) time.sleep(1) def demo_b(): # 获取线程名 t = threading.current_thread() print(t) for n in range(5): print(n, "---demo_b---", t.name) time.sleep(1) if __name__ == '__main__': # 打印线程名 t = threading.current_thread() print("欢迎进入线主程", t.name) # MainThread # 线程一 threading.Thread(target=demo_a).start() # 线程二 threading.Thread(target=demo_b).start() # 理论输出顺序为: # 欢迎进入线主程 MainThread # <Thread(Thread-1, started 123145391300608)> # <Thread(Thread-2, started 123145462067200)> # 0 ---dome_a--- Thread-1 # 0 ---demo_b--- Thread-2 # 1 ---dome_a--- Thread-1 # 1 ---demo_b--- Thread-2 # 2 ---dome_a--- Thread-1 # 2 ---demo_b--- Thread-2 # 3 ---dome_a--- Thread-1 # 3 ---demo_b--- Thread-2 # 4 ---dome_a--- Thread-1 # 4 ---demo_b--- Thread-2 # # # 实际上,因为不同线程间的相互独立,线程2不会等线程1执行完输出再执行自己的输出,所以实际输出比较混乱: # 欢迎进入线主程 MainThread # <Thread(Thread-1, started 123145391300608)> # 0 ---dome_a--- Thread-1 # <Thread(Thread-2, started 123145396555776)> # 0 ---demo_b--- Thread-2 # 1 ---dome_a--- Thread-1 # 1 ---demo_b--- Thread-2 # 2 ---dome_a---2 ---demo_b--- Thread-1 # Thread-2 # 33 ---dome_a--- ---demo_b--- Thread-2 # Thread-1 # 44 ---dome_a--- Thread-1 # ---demo_b--- Thread-2
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。