Thread模块

Thread模块是Python操作线程的库

开启线程start()

import threading


def func(i):
    print('hello', i)


for i in range(5):
    th = threading.Thread(target=func, args=(i, ))  # 创建线程对象
    th.start()  # 启动线程
hello 0
hello 1
hello 2
hello 3
hello 4

等待线程结束join()

import time
import threading


def func(i):
    time.sleep(0.5)
    print('hello', i)


th_list = list()
for i in range(5):
    th = threading.Thread(target=func, args=(i, ))  # 创建线程对象
    th.start()  # 启动线程
    th_list.append(th)

for th in th_list:
    th.join()  # 等待子线程运行结束
print('主线程运行结束')
hello 0
hello 3
hello 2
hello 1
hello 4
主线程运行结束

守护线程daemon

daemon设置为True时,守护线程会等所有的子线程结束之后才结束

使用面向对象的方式启动线程

import threading


class MyThread(threading.Thread):
    def run(self):
        print('saiya06')


th = MyThread()
th.start()
saiya06
posted @ 2022-12-06 00:24  saiya6  阅读(67)  评论(0)    收藏  举报