在学习多线程的时候看到这么一个列子。
#!/usr/local/bin/python
#coding=utf-8
import random,threading,time
from Queue import Queue
#Producer thread
class Producer(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self,name=t_name)
self.data=queue
def run(self):
for i in range(10):#随机产生10个数字 ,可以修改为任意大小
randomnum=random.randint(1,99)
print "%s: %s is producing %d to the queue!" % (time.ctime(), self.getName(), randomnum)
self.data.put(randomnum) #将数据依次存入队列
time.sleep(1)
print "%s: %s finished!" %(time.ctime(), self.getName())
#Consumer thread
class Consumer_even(threading.Thread):
def __init__(self,t_name,queue):
threading.Thread.__init__(self,name=t_name)
self.data=queue
def run(self):
while 1:
try:
val_even = self.data.get(1,5) #get(self, block=True, timeout=None) ,1就是阻塞等待,5是超时5秒
if val_even%2==0:
print "%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(),self.getName(),val_even)
time.sleep(2)
else:
self.data.put(val_even)
time.sleep(2)
except:#等待输入,超过5秒 就报异常
print "%s: %s finished!" %(time.ctime(),self.getName())
break
class Consumer_odd(threading.Thread):
def __init__(self,t_name,queue):
threading.Thread.__init__(self, name=t_name)
self.data=queue
def run(self):
while 1:
try:
val_odd = self.data.get(1,5)
if val_odd%2!=0:
print "%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(), self.getName(), val_odd)
time.sleep(2)
else:
self.data.put(val_odd)
time.sleep(2)
except:
print "%s: %s finished!" % (time.ctime(), self.getName())
break
#Main thread
def main():
queue = Queue()
producer = Producer('Pro.', queue)
consumer_even = Consumer_even('Con_even.', queue)
consumer_odd = Consumer_odd('Con_odd.',queue)
producer.start()
consumer_even.start()
consumer_odd.start()
producer.join()
consumer_even.join()
consumer_odd.join()
print 'All threads terminate!'
if __name__ == '__main__':
main()
其中Producer类实例化的时候producer = Producer('Pro.', queue)
第一个参数居然是个字符串。。初学的我表示不懂。。
这个是怎么回事,是谁处理了这个字符串??
黄舟2017-04-17 15:57:42
def __init__(self, t_name, queue):
リーリーインスタンス化されると、Python は処理のために __init__ に渡され、最初のパラメーターが t_name に割り当てられるため、この文字列は Thread の名前でもあります
黄舟2017-04-17 15:57:42
名前は threading.Thread の __init__ メソッドに渡され、name はスレッドの名前を参照します。 name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.args is the argument tuple for the target invocation. Defaults to ().