在python中,主线程结束后,会默认等待子线程结束后,主线程才退出,如下:
#coding=utf-8
import threading
import time
class mythread(threading.Thread):
def __init__(self):
super().__init__()
def run(self):
for i in range(5):
time.sleep(1)
print("mythread end")
if __name__ == "__main__":
print("main start")
thd = mythread()
thd.setDaemon(True) ##主线程在结束时结束子线程thd
thd.start()
如下面生产者、消费者模型,queue.get()队列为空时阻塞,线程consumer1还是被退出,但不会输出"consumer end"
#coding=utf-8
import time
import threading
import queue
class producer(threading.Thread):
def __init__(self,work_queue):
super().__init__() ##父类初始化
self.work_queue = work_queue
def run(self):
num = 10
while (num > 0):
self.work_queue.put(num)
num = num - 1
time.sleep(1)
print("producer end")
class consumer(threading.Thread):
def __init__(self,work_queue):
super(consumer,self).__init__() ##父类初始化
self.work_queue = work_queue
def run(self):
while True:
num = self.work_queue.get() ##queue为空时阻塞
print("get: " + str(num))
print("consumer end")
def main():
work_queue = queue.Queue()
producer1 = producer(work_queue)
producer1.start()
consumer1 = consumer(work_queue)
consumer1.setDaemon(True)
consumer1.start()
##work_queue.join()
if __name__ == '__main__':
main()
E:\MySelf\myfile\My Python>threadtest.py
get: 10
get: 9
get: 8
get: 7
get: 6
get: 5
get: 4
get: 3
get: 2
get: 1
producer end
E:\MySelf\myfile\My Python>