for i in range(10):
t=MyThread(str(i),sinal)
t.start()
sinal.set()
"""
"""python的Thread类中还提供了join()方法,使得一个线程可以等待另一个线程执行结束后再继续运行。这个方法还可以设定一个timeout参数,避免无休止的等待。因为两个线程顺序完成,看起来象一个线程,所以称为线程的合并.对于sleep时间过长的线程,将不被等待。
import threading
import random
import time
class MyThread(threading.Thread):
def run(self):
wait_time=random.randrange(1,10)
print '%s will wait %d seconds'%(self.name,wait_time)
time.sleep(wait_time)
print '%s wakes up!' %self.name
if __name__=='__main__':
threads=[]
for i in range(5):
t=MyThread()
t.start()
threads.append(t)
print 'main thread is waiting for exit...'
for t in threads:
t.join(1)
print 'main thread finished!'
后台线程
默认情况下,主线程在退出时会等待所有子线程的结束。如果希望主线程不等待子线程,而是在退出时自动结束所有的子线程,就需要设置子线程为后台线程(daemon)。方法是通过调用线程类的setDaemon()方法。如下:
import threading
import random
import time
class MyThread(threading.Thread):
def run(self):
wait_time=random.randrange(1,10)
print '%s will wait %d seconds'%(self.name,wait_time)
time.sleep(wait_time)
print '%s finished!' %self.name
if __name__=='__main__':
print 'main thread is waitting for exit.....'
for i in range(5):
t=MyThread()
t.setDaemon(True)
t.start()
import threading
import time
from Queue import Queue
class Producer(threading.Thread):
def run(self):
global queue
count=0
while True:
for i in range(100):
if queue.qsize()>1000:
pass
else:
count=count+1
msg='produce '+str(count)
queue.put(msg)
print msg
time.sleep(1)
class Consumer(threading.Thread):
def run(self):
global queue
while True:
for i in range(3):
if queue.qsize()<100:
pass
else:
msg=self.name+'consume '+ queue.get()
print msg
time.sleep(1)
queue=Queue()
def test():
for i in range(500):
queue.put('product '+ str(i))
print 'finished'
for i in range(2):
p=Producer()
p.start()
for i in range(5):
c=Consumer()
c.start()