Python多线程练习(一)

aries 发表于 2012-10-21 1175 次浏览
#! /usr/bin/env python
#coding=utf-8
# FIlename ex1.py
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()
输出结果:
thread 0 is running 0
thread 1 is running 0
thread 2 is running 0
thread 0 is running 1
thread 1 is running 1
thread 2 is running 1
thread 0 is running 2
thread 1 is running 2
thread 2 is running 2
thread 0 is running 3
thread 1 is running 3
thread 2 is running 3
thread 0 is running 4
thread 1 is running 4
thread 2 is running 4
[Finished in 5.2s]
从输出结果可以看到,3个线程是交替的执行的

0条评论

如需评论,请填写表单。
换一个

记住我的信息