posts - 431,  comments - 344,  trackbacks - 0

          from Queue import Queue
          import threading
          import random
          import time

          class Producer(threading.Thread):
              def __init__(self, threadname, queue):
                  threading.Thread.__init__(self, name=threadname)
                  self.sharedata = queue
              def run(self):
                  for i in range(10):
                      print self.getName(), 'adding', i, 'to queue'
                      self.sharedata.put(i)
                      time.sleep(random.randrange(10)/10.0)
                  print self.getName(), 'Finished'
          class Consumer(threading.Thread):
              def __init__(self, threadname, queue):
                  threading.Thread.__init__(self, name=threadname)
                  self.sharedata = queue
              def run(self):
                  for i in range(10):
                      print self.getName(), 'get a value', self.sharedata.get()
                      time.sleep(random.randrange(10)/10.0)
                  print self.getName(), 'Finished'
          def main():
              queue = Queue()
              producer = Producer('Producer', queue)
              consumer = Consumer('Consumer', queue)
              print 'Starting threads...'
              producer.start()
              consumer.start()
             
              producer.join()
              consumer.join()
              print 'All threads have terminated.'
             
          if __name__ == '__main__':
              main()


          如何來(lái)獲得與線程有關(guān)的信息呢?

          獲得當(dāng)前正在運(yùn)行的線程的引用

          running = threading.currentThread()

          獲得當(dāng)前所有活動(dòng)對(duì)象(即run方法開(kāi)始但是未終止的任何線程)的一個(gè)列表

          threadlist = threading.enumerate()

          獲得這個(gè)列表的長(zhǎng)度

          threadcount = threading.activeCount()

          查看一個(gè)線程對(duì)象的狀態(tài)調(diào)用這個(gè)線程對(duì)象的isAlive()方法,返回1代表處于“runnable”狀態(tài)且沒(méi)有“dead

          threadflag = threading.isAlive()

          posted on 2007-09-25 15:51 周銳 閱讀(246) 評(píng)論(0)  編輯  收藏 所屬分類: Python
          主站蜘蛛池模板: 行唐县| 阳江市| 改则县| 裕民县| 易门县| 平乡县| 山阳县| 广宁县| 巴马| 湖北省| 玉山县| 邵东县| 淮滨县| 连城县| 漳州市| 武鸣县| 蒙山县| 来凤县| 湘潭市| 年辖:市辖区| 肇东市| 塔河县| 萨迦县| 济宁市| 罗定市| 奈曼旗| 道孚县| 辉县市| 垣曲县| 洪雅县| 梁山县| 禄劝| 阳信县| 柞水县| 萝北县| 滕州市| 中江县| 临城县| 岢岚县| 诸暨市| 萍乡市|