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()
如何來獲得與線程有關的信息呢?
獲得當前正在運行的線程的引用
running = threading.currentThread()
獲得當前所有活動對象(即run方法開始但是未終止的任何線程)的一個列表
threadlist = threading.enumerate()
獲得這個列表的長度
threadcount = threading.activeCount()
查看一個線程對象的狀態調用這個線程對象的isAlive()方法,返回1代表處于“runnable”狀態且沒有“dead”
threadflag = threading.isAlive()
posted on 2007-09-25 15:51
周銳 閱讀(245)
評論(0) 編輯 收藏 所屬分類:
Python