python-多个线程的运行顺序

概述

本节通过编码,观察多线运行的顺序。

执行下面的代码,运行且观察结果:

#coding=utf-8
import threading
import time
import os

def task(index):
    #任务
    while True:
        #获取当前线程对象
        t=threading.current_thread()
        print('task-%d,name=%s'%(index,t.name))
        time.sleep(2)

if __name__ == "__main__":
    print('pid=%d'%os.getpid())
    for index in range(5):
        #创建线程,并传值
        t=threading.Thread(target=task,args=(index,))
        t.start()
        #打印线程名
        print('启动线程-%d,name=%s'%(index,t.name))

    while True:
        print('主线程,存活线程数量=%d'%(threading.active_count()))
        time.sleep(2)

执行结果如下:

经过多次运行,观察发现,主线程和子线程执行的顺序是乱序的