网站制作学习网Python→正文:python 多线程 并发
字体:

python 多线程 并发

Python 2022/4/11 19:31:38  点击:不统计


"""
通过类执行多线性的方法,实现并发,下面代码,直接复制,保存为.py文件即可执行

@ author www.forasp.cn
@ 多线程调用,python 多线程 

@ info : 多线程处理
"""
# 引入多线程类库
import threading
 
 
# 定义类 或者定义函数方法
class Main(threading.Thread):
    def __init__(self, thread_id, thread_name):
        super(Main, self).__init__()
        self.thread_id = thread_id
        self.thread_name = thread_name
        pass
 
    def run(self):
        for i in range(1, 10):
            print("运行", self.thread_name, "输出", i)
 
 
# 多线程调用
if __name__ == "__main__":
    # 分别是 thread id 和thread name
    thread_name = {
        1: "网站",
        2: "制作",
        3: "学习",
        4: "网"
    }
#定义多线程句柄数组
    thread_names = locals()
#循环创建多线程,并开始运行
    for item in thread_name:
        class_id = item
        class_name = thread_name[item]
        thread_names["p_thread" + str(class_id)] = Main(class_id, class_name)
        # 多线程开始必须是 start 方法
        thread_names["p_thread" + str(class_id)].start()
    pass

# 以上是通过类的方法进行多线程实现,下面代码 则是通过 函数的方式,进行多线程的执行,同样
# 下面代码可以直接保存为.py文件可以测试运行


"""
@ author www.forasp.cn 
@ info : 多线程处理,通过方法进行操作
"""
# 引入线程类
import _thread
import random
import threading
import time
 
 
def main(thread_id, thread_name):
    # 更改进程数量 为全局
    global unfinished_thread_num
    for i in range(1, 10):
        sleep_time = random.randint(0, 10)
        print("线程ID:", thread_id, "运行", thread_name, "输出", i, "后休息", sleep_time, "秒")
        time.sleep(sleep_time)
 
    lock.acquire()
    # 加锁后,减少没有完成的进程数量
    unfinished_thread_num -= 1
    print("线程ID", thread_id, "完毕,减去未完成")
    # 数据更新后 解锁
    lock.release()
 
 
#多线程调用
if __name__ == "__main__":
    # 定义 多线程未完成数量
    unfinished_thread_num = 0
    # 定义线程锁
    lock = threading.Lock()
    # 分别是 thread id 和thread name
    thread_names = {
        1: "网站",
        2: "制作",
        3: "学习",
        4: "网"
    }
    for item in thread_names:
        thread_id = item
        thread_name = thread_names[item]
        print("启动线程名称:", thread_name, "线程ID", thread_id)
        # 线程开水 第一个参数为
        try:
            _thread.start_new_thread(main, (thread_id, thread_name))
            # 增加线程数量, 先加锁
            lock.acquire()
            print("新增未完成进程", thread_id)
            unfinished_thread_num += 1
            # 数据更新后 解锁
            lock.release()
        except:
            print("多线程调用失败")
    # 等待线程执行
    while True:
        # 如果所有线程都执行完毕,则跳出
        if unfinished_thread_num == 0:
            print("多线程执行完毕")
            break
    pass
 
# 代码结束,可以试试哦,很容易理解,上面每段代码都有注释


·上一篇:python 字符串替换 >>    ·下一篇:Beutifulsoap 获取链接 a 文本内容 >>
推荐文章
最新文章