多线程2

多线程2

两个线程

以下代码演示两个线程同时进行的情况:

import threading
import time


def thread1_job():
    print("thread1 start")
    for i in range(10):
        time.sleep(0.1)
    print('thread1 complete')

def thread2_job():
    print("thread2 start")
    for i in range(5):
        time.sleep(0.1)
    print('thread2 complete')

def main():
    thread1 = threading.Thread(target=thread1_job)
    thread2 = threading.Thread(target=thread2_job)
    
    thread1.start()
    thread2.start()
    print('\nall done')


if __name__ == '__main__':
    main()

输出结果:

thread1 start
thread2 start
thread2 complete
thread1 complete

all done

thread1先执行,thread2后执行,而thread2比thread1先完成。

这是因为thread1所需的时间比thread2长,两者开始的时间很接近,在thread1开始后,thread1还未完成,thread2就开始执行,两者同时在运行。

在所有线程完成后,才能继续运行main函数中的print。

join功能

接下来把thread1的join功能放在thread2开始之前,下面的代码与上面的区别仅在第22行:

import threading
import time


def thread1_job():
    print("thread1 start")
    for i in range(10):
        time.sleep(0.1)
    print('thread1 complete')

def thread2_job():
    print("thread2 start")
    for i in range(5):
        time.sleep(0.1)
    print('thread2 complete')

def main():
    thread1 = threading.Thread(target=thread1_job)
    thread2 = threading.Thread(target=thread2_job)

    thread1.start()
    thread1.join()
    thread2.start()
    print('\nall done')


if __name__ == '__main__':
    main()

输出结果:

thread1 start
thread1 complete
thread2 start
all done

thread2 complete

thread1的join功能使下面的语句等thread1执行完毕才运行。

也就是说程序运行到第22行时,join使程序停止,直到thread1的任务执行完毕后,程序才继续运行第23行。

posted on 2021-08-27 22:38  菜小疯  阅读(24)  评论(0编辑  收藏  举报