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
          主站蜘蛛池模板: 宁远县| 独山县| 璧山县| 城步| 社会| 临澧县| 磴口县| 名山县| 吴忠市| 宁德市| 白玉县| 库尔勒市| 德江县| 旅游| 固阳县| 遂平县| 微山县| 临澧县| 公主岭市| 桐庐县| 阿巴嘎旗| 饶河县| 灵寿县| 普洱| 全州县| 邓州市| 郓城县| 大石桥市| 蒲城县| 桦川县| 剑川县| 大城县| 丹巴县| 城市| 安乡县| 江津市| 平乐县| 兴义市| 墨竹工卡县| 云安县| 云林县|