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()


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

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

          running = threading.currentThread()

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

          threadlist = threading.enumerate()

          獲得這個列表的長度

          threadcount = threading.activeCount()

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

          threadflag = threading.isAlive()

          posted on 2007-09-25 15:51 周銳 閱讀(246) 評論(0)  編輯  收藏 所屬分類: Python
          主站蜘蛛池模板: 那曲县| 安图县| 峨山| 安丘市| 镇巴县| 珠海市| 航空| 彭山县| 宣武区| 永和县| 枞阳县| 沂水县| 崇义县| 乐清市| 招远市| 静安区| 西乌珠穆沁旗| 宁陵县| 南陵县| 二连浩特市| 阿拉善右旗| 汉川市| 安达市| 汉中市| 新安县| 苗栗市| 祁东县| 巴马| 博兴县| 衡水市| 红安县| 甘德县| 福清市| 时尚| 临邑县| 兴业县| 商南县| 中西区| 华亭县| 镇原县| 日土县|