python中对线程支持友好,有对应的第三方包。threading(推荐使用)
threading()和函数搭配,然后start启动就可以。具体,请看案例。
import time
from threading import Thread
def hello():
print('hellos')
time.sleep(5)
print('gaoci')
def hi():
print('hi')
time.sleep(5)
print('GAOCI')
if __name__ == '__main__':
"""
实例化线程,传入需要处理的值,===创建子线程
"""
hello_thread = Thread(target=hello)
hi_thread = Thread(target=hi)

"""
线程的名称,没有命名默认为thread1……
"""
# hello_thread.setName('hello_name')#设置线程名称
# hi_thread.setName('hi_name')
# print(hello_thread.getName())#获得线程名称
# print(hi_thread.getName())
"""
是否开启守护线程,主线程die掉,子线程也die掉
"""
hello_thread.setDaemon(True)
hi_thread.setDaemon(True)
"""
开启线程
"""
hello_thread.start()
hi_thread.start()

print('主线程加载结束')

"""
阻塞主线程的作用
"""
# hello_thread.join()
# hi_thread.join()