python多任务(线程、进程、协程)_2

线程的创建

python多任务(线程、进程、协程)_2_第1张图片

通过sleep让某些线程先执行

import threading,time
def test1():
    for i in range(5):
        print("-----test1-------" + str(i))

def test2():
    for i in range(5):
        print("-----test2-------" + str(i))


def main():
    t1 = threading.Thread(target=test1)   #创建对象
    t2 = threading.Thread(target=test2)    #创建对象
    t1.start()                              #创建子进程
    time.sleep(1)
    t2.start()                              #创建子进程

    print(threading.enumerate())


if __name__ == "__main__":
    main()





-----test1-------0
-----test1-------1
-----test1-------2
-----test1-------3
-----test1-------4
-----test2-------0[<_MainThread(MainThread, started 6668)>, ]

-----test2-------1
-----test2-------2
-----test2-------3
-----test2-------4


循环查看当前运行的线程

import threading,time
def test1():
    for i in range(3):
        print("-----test1-------" + str(i))
        time.sleep(1)


def test2():
    for i in range(4):
        print("-----test2-------" + str(i))
        time.sleep(1)

def main():
    t1 = threading.Thread(target=test1)   #创建对象
    t2 = threading.Thread(target=test2)    #创建对象
    t1.start()                              #创建子进程
    t2.start()                              #创建子进程

    while True:
        print(threading.enumerate())
        if len(threading.enumerate())<=1:
            break
        time.sleep(1)

if __name__ == "__main__":
    main()






-----test1-------0
-----test2-------0[<_MainThread(MainThread, started 3620)>, , ]

[<_MainThread(MainThread, started 3620)>, , ]-----test1-------1

-----test2-------1
[<_MainThread(MainThread, started 3620)>, , ]
-----test1-------2
-----test2-------2
[<_MainThread(MainThread, started 3620)>, , ]
-----test2-------3
[<_MainThread(MainThread, started 3620)>, ]
[<_MainThread(MainThread, started 3620)>]

python多任务(线程、进程、协程)_2_第2张图片

你可能感兴趣的:(python)