python 多线程threading

推荐一个不错的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]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值