您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章将为大家详细讲解有关Python如何批量启动多线程,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
建立一个线程池,并将某个线程放入进去
threadpool = [] th = threading.Thread(target=func_name, args=func_args) threadpool.append(th)
批量加入线程
for i in range(10): th = threading.Thread(target=func_name, args=func_args) threadpool.append(th)
批量开始线程
for th in threadpool: th.start() for th in threadpool: threading.Thread.join(th)
实例如下:
#!/usr/bin/python3.4
# -*- coding: utf-8 -*-
import time
import threading
def matter1(music, test):
print(test, music)
# 假设每一首歌曲的时间是2秒
time.sleep(2)
if __name__ == '__main__':
# 设定我要听的歌为
musics = ["music1", "music2", "music3"]
test = "122678"
# 开始时间
start = time.time()
threadpool = []
# 传入多个参数
for music in musics:
# 传入单个参数请写成
# args=(arg1,)
th = threading.Thread(target=matter1, args=(music, test))
threadpool.append(th)
for th in threadpool:
th.start()
for th in threadpool:
threading.Thread.join(th)
# 结束时间
end = time.time()
print("完成的时间为:" + str(end - start))完成同时听三首歌线程,花费时间 2s:
关于“Python如何批量启动多线程”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。