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
周銳 閱讀(244)
評(píng)論(0) 編輯 收藏 所屬分類:
Python