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
周銳 閱讀(421)
評論(0) 編輯 收藏 所屬分類:
Python