python线程的批量创建

上篇文章介绍了python线程的基础知识和创建的方法,现在开始介线程的批量创建的方法。

在python3 中创建线程有两种方式,一种是通过threading.Thread直接创建线程并运行,一种是通过继承threading.Thread 类来创建线程。

1.用thread.Thread 直接在线程中运行函数

import threading
def worker(name):
    print("thread %s is runing" % name)
worker = threading.Thread(target = worker,args = ('worker',))
worker.start()
worker.join()

运行结果如下:


2.通过继承thread.Thread 来创建线程

import threading
class MyThread(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)       #这一步是必须的,不加会报错
        self.name = name
    def run(self):
        for i in range(5):
            print("thread %s is runing-----%s" %(self.name,i))
worker1 = MyThread('worker1')
worker2 = MyThread('worker2')

worker1.start()
worker2.start()

worker1.join()
worker2.join()
运行结果如下:
thread worker1 is runing-----0thread worker2 is runing-----0

thread worker1 is runing-----1thread worker2 is runing-----1

thread worker1 is runing-----2thread worker2 is runing-----2

thread worker1 is runing-----3thread worker2 is runing-----3

thread worker1 is runing-----4thread worker2 is runing-----4




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值