posts - 431,  comments - 344,  trackbacks - 0
          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 周銳 閱讀(423) 評論(0)  編輯  收藏 所屬分類: Python
          主站蜘蛛池模板: 龙南县| 南城县| 英德市| 陕西省| 东阳市| 进贤县| 江华| 聊城市| 葵青区| 连山| 历史| 杨浦区| 台中市| 礼泉县| 河源市| 丹阳市| 和平区| 稻城县| 肥西县| 岳西县| 同德县| 井冈山市| 南宫市| 安顺市| 昌图县| 海原县| 抚远县| 民县| 荥经县| 富川| 兴化市| 双峰县| 墨江| 滦南县| 长汀县| 嵊泗县| 麻城市| 广州市| 眉山市| 汉川市| 兴业县|