进程/线程切换原则

'''
多个子线程执行相同代码,先开的子线程不一定先执行完毕,如果子线程内有IO操作/time.sleep等
IO操作/time.sleep会导致子线程切出到其他线程(包括主线程)
如果没有引起线程切换,则顺序执行完毕
进程/线程切换原则
    1 时间片
    2 遇到io操作切换
    3 优先级切换
'''

import time,threading

l=[]

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        global l

        #可将此句取消注释对比运行结果
        # time.sleep(0.0000000000001)

        #将当前线程名添加到列表l
        l.append(self.getName())

for i in range(50):
    t=MyThread()
    t.start()

l.append('主线程')
#不确定join是否干扰子线程运行,用sleep保证子线程运行完毕
time.sleep(2)
print(l)
原文地址:https://www.cnblogs.com/yx179971/p/7229969.html