初窥Python线程

初窥Python线程


 1# author: wangy
 2# date: 2024/7/24
 3# description: 初窥线程
 4
 5"""
 6Python的线程模型参考了Java的线程模型.
 7
 8Python的线程模型由threading标准库提供:
 9https://docs.python.org/zh-cn/3/library/threading.html
10"""
11from threading import Thread
12from threading import current_thread
13
14
15# ############### #
16#     创建线程     #
17# ############### #
18class MyThread(Thread):
19    """
20    直接继承Thread类来创建线程,需要重写run()方法
21    """
22
23    def run(self):
24        time.sleep(1)
25        print(f"{current_thread().name} is running...")
26
27
28def creat_thread_by_extend():
29    for i in range(5):
30        t = MyThread()
31        t.start()
32        # thread.join() 在当前线程上等待thread线程运行完成
33        t.join()
34
35    # MainThread
36    print(f"{current_thread().name} done...")
37
38
39def thread_func(name):
40    time.sleep(1)
41    print(f"{name} is running...")
42
43
44def create_thread_by_constructor():
45    """
46    通过构造器创建线程,实际上就是开启新线程运行某个函数
47    """
48    for i in range(5):
49        t = Thread(target=thread_func, args=(f"c-thread-{i + 1}",))
50        t.start()
51        t.join()
52    print(f"{current_thread().name} done...")
53
54
55# python 模块的main方法
56if __name__ == '__main__':
57    creat_thread_by_extend()
58    create_thread_by_constructor()