python queue 生产者 消费者_使用Queue实现生产者和消费者

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值