5.28学习总结thread多线程理解

发布时间 2023-06-11 10:47:29作者: cassebl

多线程早在大二刚来的时候就听王建民老师提到过,但是当时觉得多线程肯定很难,而且现在也用不到,就没有接触。现在看来多线程的学习还是比较简单的。

下面演示代码均为Python

from threading import Thread


th = thread(target=,args=())  # target指向新线程执行的目标函数,args中为传递的参数

thread.start()  # 创建新线程

我们发现thread和按钮的形式有些相似,都有着绑定目标函数和传递参数这个两个emmm...属性,不同的是按钮的执行是在主线程中,而thread会在新的线程中执行新函数。

from threading import Thread
from time import sleep

def threadFunc():
    sleep(2)
    print('子线程 结束')  # 等待2s

thread = Thread(target=threadFunc)
thread.start()
print('主线程结束')

更详细的学习,我推荐——多线程 和 多进程 | 白月黑羽 (byhy.net)