python线程HelloWorld
改变num的值可以控制线程的数量
弄它几千个不是问题
呵呵
每个线程启动后会随机睡眠1-3秒
醒来后结束
[code]
#!/usr/bin/env python
import threading
import time
import random
class PrintThread(threading.Thread):
def __init__(self, threadName):
threading.Thread.__init__(self, name = threadName)
self.sleepTime = random.randint(1,3)
print "Name: %s; sleep: %d" % (self.getName(), self.sleepTime)
def run(self):
print "%s going to sleep for %s second(s)"\
% (self.getName(), self.sleepTime)
time.sleep(self.sleepTime)
print self.getName(), 'done sleeping'
num=10
threadList=[]
for i in range(1,num+1):
thread = PrintThread('thread'+str(i))
threadList.append(thread)
print '\nStarting threads'
for i in threadList:
i.start()
print 'All threads started\n'
for i in threadList:
i.join()
print 'All threads stoped\n'
[/code]
线程同步可以用锁
现在让我们一起回到遥远的DOS时代
还是上面的程序
但是每一时刻只有一个线程可以工作
只是增加了三行代码而已
[code]
#!/usr/bin/env python
import threading
import time
import random
class PrintThread(threading.Thread):
def __init__(self, threadName):
threading.Thread.__init__(self, name = threadName)
self.sleepTime = random.randint(1,3)
print "Name: %s; sleep: %d" % (self.getName(), self.sleepTime)
def run(self):
lock.acquire() #add this
print "%s going to sleep for %s second(s)"\
% (self.getName(), self.sleepTime)
time.sleep(self.sleepTime)
print self.getName(), 'done sleeping'
lock.release() #add this
num=10
threadList=[]
lock=threading.RLock() #add this
for i in range(1,num+1):
thread = PrintThread('thread'+str(i))
threadList.append(thread)
print '\nStarting threads'
for i in threadList:
i.start()
print 'All threads started\n'
for i in threadList:
i.join()
print 'All threads stoped\n'
[/code]
posted on 2007-09-25 13:50
周锐 阅读(417)
评论(0) 编辑 收藏 所属分类:
Python