当前位置: 编程技术>python
python创建线程示例
来源: 互联网 发布时间:2014-10-04
本文导语: 代码如下:import threadingfrom time import sleep def test_func(id): for i in range(0,5): sleep(1) print('thread %d is running %d' % (id,i)) threads = []for i in range(0,3): t = threading.Thread(target=test_func, args=(i,)) threads.append(t) for t ...
代码如下:
import threading
from time import sleep
def test_func(id):
for i in range(0,5):
sleep(1)
print('thread %d is running %d' % (id,i))
threads = []
for i in range(0,3):
t = threading.Thread(target=test_func, args=(i,))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
从输出结果可以看到,3个线程是交替的执行的