python 多线程threading

本文介绍了一个实用的Python多线程教程,通过继承threading.Thread类实现多线程功能。文章提供了一个具体示例,展示了如何创建和启动多个线程,并使主线程等待这些线程完成。
部署运行你感兴趣的模型镜像

推荐一个不错的python教程

https://www.tutorialspoint.com/python/python_multithreading.htm

这里的多线程写的很nice, 例子很容易懂

我的例子如下:

multiThreadingRun继承threading.Thread的class只需要override __init__和run方法,使用时,实例化multiThreadingRun并传入threadName,方法func, 方法参数*args即可

import threading
import time
class multiThreadingRun(threading.Thread):
	def __init__(self, threadName, func, *args):
		threading.Thread.__init__(self)
		self._func = func
		self._args = args
		self.threadName = threadName

	def run(self):
		print("Starting " + self.threadName)
		self._func(*self._args)
		print("Exiting " + self.threadName)


def print_time(threadName, counter, delay):
	while counter:
		time.sleep(delay)
		print("%s: %s"%(threadName, time.ctime(time.time())))
		counter -= 1

aa_list = ["thread1", "thread2", "thread3"]
my_threadings = []
for aa in aa_list:
	my_threading = multiThreadingRun(aa, print_time, aa, 5, 1)
	my_threading.start()
	my_threadings.append(my_threading)

for my_threading in my_threadings:
	my_threading.join()

输出:

Starting thread1
Starting thread2
Starting thread3
thread2: Tue Aug 21 13:00:49 2018
thread3: Tue Aug 21 13:00:49 2018
thread1: Tue Aug 21 13:00:49 2018
thread3: Tue Aug 21 13:00:50 2018
thread2: Tue Aug 21 13:00:50 2018
thread1: Tue Aug 21 13:00:50 2018
thread3: Tue Aug 21 13:00:51 2018
thread2: Tue Aug 21 13:00:51 2018
thread1: Tue Aug 21 13:00:51 2018
thread2: Tue Aug 21 13:00:52 2018
thread1: Tue Aug 21 13:00:52 2018
thread3: Tue Aug 21 13:00:52 2018
thread3: Tue Aug 21 13:00:53 2018
Exiting thread3
thread2: Tue Aug 21 13:00:53 2018
Exiting thread2
thread1: Tue Aug 21 13:00:53 2018
Exiting thread1
[Finished in 5.4s]

 

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值