思考:在python应用程序中能否执行个2个以上的无限循环呢?
单线程的问题
意味着一个进程中只有一条执行路径,特点就是可以分析出来该程序是如何执行的
# 单线程:一个进程中只有一条执行路径
# 特性:可以分析出来程序是如何执行的
class Test(object):
def __init__(self,name):
self.name = name
def run(self):
for i in range(3):
print(f'{self.name} --> run ... {i}')
# main test
if __name__ == '__main__':
print('main start....')
# 1.test object
test_one = Test('one')
test_one.run()
test_two = Test('two')
test_two.run()
for i in range(3):
print(f'main --> run ... {i}')
print('main finish...')
这里的问题在于如果线程one不执行完成,线程two是没有机会执行的,two执行不完,main就会被永远卡住,现实中这样的低效是会让用户体验非常糟糕
多线程
在商业化的应用设计时候,通常会为一个程序设计多个线程,大都不会让一个线程占据系统所有资源,例如,word设计时候,由一个线程是处理编辑窗口随时监听是否由屏幕输入可以实时编排版面,同一时间也有word的线程在做编辑字数统计随时更新word的窗口状态栏。
多线程执行特点
乱序执行,多线程的任务是没有办法分析执行流程的,这是由操作系统的调度决定的
import threading
# 获取主线程
thread = threading.main_thread()
print(thread, id(thread))
# 获取当前线程
current_thread = threading.current_thread()
print(current_thread, id(current_thread))
# 因为当前程序只有一个线程即主线程,所以main线程就是current_thread
# 当前的活跃线程
threading_active_count = threading.active_count()
print(threading_active_count)
执行结果
多线程初体验:多个死循环线程同时执行
import threading
# 任务输出
def thread_body():
t = threading.current_thread()
# 死循环
while True:
print(f'{t.name} 线程正在执行中')
# threading.Thread来创建线程,target关键字是表示子线程执行的任务,target接收的是一个函数对象名称
if __name__ == '__main__':
t1 = threading.Thread(target=thread_body)
t2 = threading.Thread(target=thread_body)
# 启动线程
t1.start()
t2.start()
# 主线程代码
while True:
print(f'{threading.current_thread()} 线程正在执行中')
资源利用率开始拉满
结束python程序
主线程与子线程的关系