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


如何来获得与线程有关的信息呢?

获得当前正在运行的线程的引用

running = threading.currentThread()

获得当前所有活动对象(即run方法开始但是未终止的任何线程)的一个列表

threadlist = threading.enumerate()

获得这个列表的长度

threadcount = threading.activeCount()

查看一个线程对象的状态调用这个线程对象的isAlive()方法,返回1代表处于“runnable”状态且没有“dead

threadflag = threading.isAlive()

posted on 2007-09-25 15:51 周锐 阅读(241) 评论(0)  编辑  收藏 所属分类: Python

只有注册用户登录后才能发表评论。


网站导航: