1.主线程与子线程
主线程与子线程的概念
-----------------------------
主线程:当一个程序启动时,就有一个线程开始运行(由上往下运行)
该线程通常叫做程序的主线程
子线程:因为程序是开始时就执行的,如果需要再创建线程,
那么创建的线程就是这个主线程的子线程
主线程的重要性体现在两个方面:
1.是产生其子线程的线程
2.通常它必须最后完成执行,比如执行各种关闭操作
2.join
join: 阻塞调用程序(主线程),直到调用join的子线程结束
(转下一个添加了join的子线程结束,所有添加了join的子线程结束)
才会继续执行主线程
join原理: 依次判断线程池中线程是否结束,
没有结束就阻塞主线程直到结束,
这个线程池当中的线程结束了,
就会跳到下一个有join的线程中
import threading
import time
def run(name):
print('*'*30, f'Child thread: {name}', '*'*30)
time.sleep(2)
print('子线程结束')
th_yuan = threading.Thread(target=run, args=('测试1',))
th_yuan.start()
print('主线程结束')
"""
****************************** Child thread: 测试1 ******************************
主线程结束
子线程结束
"""
import threading
import time
def run(name):
print('*'*30, f'Child thread: {name}', '*'*30)
time.sleep(2)
print('子线程结束')
th_yuan = threading.Thread(target=run, args=('测试1',))
th_yuan.start()
th_yuan.join()
print('主线程结束')
"""
****************************** Child thread: 测试1 ******************************
子线程结束
主线程结束
"""
3.setDaemon
setDaemon与join基本上是相对的,join会等子线程执行完;而setDaemon不会
setDaemon:守护线程---主线程结束,子线程也跟着结束
import threading
import time
def demo(name):
print('*'*30, f'Child thread: {name}', '*'*30)
time.sleep(2)
print('子线程结束')
th_yuan = threading.Thread(target=demo, args=('测试2',))
th_yuan.start()
print('主线程结束')
"""
****************************** Child thread: 测试2 ******************************
主线程结束
子线程结束
"""
import threading
import time
def demo(name):
print('*'*30, f'Child thread: {name}', '*'*30)
time.sleep(2)
print('子线程结束')
th_yuan = threading.Thread(target=demo, args=('测试2',))
th_yuan.setDaemon(True)
th_yuan.start()
print('主线程结束')
"""
****************************** Child thread: 测试2 ******************************
主线程结束
"""