精易论坛

标题: Python简单实现多线程例子 [打印本页]

作者: a475972878    时间: 2024-6-7 12:18
标题: Python简单实现多线程例子
使用Python实现多线程的例子,演示如何在主线程内分别启动ABC三个线程,并实现启动和停止指定线程的功能

[Python] 纯文本查看 复制代码
import threading
import time

# 定义一个全局标志,用于控制线程的运行状态
stop_thread_A = False
stop_thread_B = False
stop_thread_C = False

# 线程A的函数
def thread_A():
    while not stop_thread_A:
        print("Thread A is running")
        time.sleep(1)
    print("Thread A is stopped")

# 线程B的函数
def thread_B():
    while not stop_thread_B:
        print("Thread B is running")
        time.sleep(1)
    print("Thread B is stopped")

# 线程C的函数
def thread_C():
    while not stop_thread_C:
        print("Thread C is running")
        time.sleep(1)
    print("Thread C is stopped")

# 启动线程的函数
def start_threads():
    global thread_a, thread_b, thread_c

    # 创建线程
    thread_a = threading.Thread(target=thread_A)
    thread_b = threading.Thread(target=thread_B)
    thread_c = threading.Thread(target=thread_C)

    # 启动线程
    thread_a.start()
    thread_b.start()
    thread_c.start()

# 停止指定线程的函数
def stop_thread(thread_name):
    global stop_thread_A, stop_thread_B, stop_thread_C

    if thread_name == 'A':
        stop_thread_A = True
    elif thread_name == 'B':
        stop_thread_B = True
    elif thread_name == 'C':
        stop_thread_C = True

if __name__ == "__main__":
    # 启动ABC三个线程
    start_threads()

    # 主线程等待5秒
    time.sleep(5)

    # 停止线程A
    stop_thread('A')

    # 主线程等待5秒
    time.sleep(5)

    # 停止线程B和C
    stop_thread('B')
    stop_thread('C')

    # 确保所有线程已经停止
    thread_a.join()
    thread_b.join()
    thread_c.join()

    print("All threads have been stopped")


注意事项这个示例展示了如何使用Python的threading模块来启动和停止线程,并解释了相关的注意事项和代码细节。


作者: boofan    时间: 2024-8-24 11:09
你好 大佬怎么联系
作者: 花椒    时间: 2024-8-29 23:03
有没有易语言的




欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4