Queue队列有2个方法put和get方法put 是把共享数据放入队列,get是取出共享数据
put从队列的尾部放入,get从队列的头部读出。
Queue接受2个参数,一个是队列大小,小于1的队列大小,被认为是无限队列,另一个是同步方式,其中1为阻塞方式,0为触发异常。
其实,用Queue来达到线程同步,是非常简单的,因为Queue本省就是线程安全的。不需要额外的锁和条件变量,看例子:
#coding=utf-8
#file name is maker.py
import threading
import random
import time
class Maker(threading.Thread):
def __init__(self,threadName,shareObject):
threading.Thread.__init__(self,name=threadName)
self.shareObject=shareObject
def run(self):
for i in range(1,11):
time.sleep(random.randrange(1,4))
self.shareObject.put(i)
print "%s threading put %d" %(threading.currentThread().getName(),i)
=========================================================
#coding=utf-8
#file name is user.py
import threading
import time
import random
class User(threading.Thread):
def __init__(self,threadName,shareObject):
threading.Thread.__init__(self,name=threadName)
self.shareObject=shareObject
self.sum=0
def run(self):
for i in range(1,11):
time.sleep(random.randrange(1,4))
tempNum=self.shareObject.get()
print "%s threading get %d" %(threading.currentThread().getName(),tempNum)
self.sum=self.sum+tempNum
def display(self):
print "end sum is %d" %(self.sum)
=======================================================
#coding=utf-8#file name is test.py
from maker import Maker
from user import User
import Queue
quere=Queue.Queue()
maker1=Maker("maker",quere)
user1=User("user",quere)
user1.start()
maker1.start()
maker1.join()
user1.join()
user1.display()
print "main threading is over!"