python多线程

import threading

import time

两种方式,注意线程的调度时间sleep不要设置太大,越小cpu的使用率就会越高,并行效果越明显!

(1)直接调用threading创建线程

def print_age(who, age):

""" 需要用多线程调用的函数 :param who: :param age: :return: """

print("Hello,every one!")

time.sleep(1)

print("%s is %s years old !" % (who, age))

if __name__ == "__main__":

t1 = threading.Thread(target=print_age, args=("jet", 18, )) # 创建线程1

t2 = threading.Thread(target=print_age, args=("jack", 25, )) # 创建线程2

t3 = threading.Thread(target=print_age, args=("jack", 25,)) # 创建线程3

t1.start() # 运行线程1

t2.start() # 运行线程2

t3.start() # 运行线程3

print("over...")

(2)通过继承重写run方法

import threading

import time

class MyThread(threading.Thread):

""" 使用继承的方式实现多线程 """

def __init__(self, who):

    super().__init__() # 必须调用父类的构造方法

    self.name = who def run(self): print("%s is run..." % self.name)

    time.sleep(3)

if __name__ == "__main__":

   t1 = MyThread("Jet") # 创建线程1

   t2 = MyThread("Jack") # 创建线程2

   t1.start() # 运行线程1

t2.start() # 运行线程2

print("over...")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值