python 对于多线程的用途的理解

import threading
import time

def print_age(who, age):
    """
    需要用多线程调用的函数
    :param who:
    :param age:
    :return:
    """
    print("Hello,every one!")
    time.sleep(5)
    print("%s is %s years old !" % (who, age))

def print_ht(who, ht):
    """
    需要用多线程调用的函数
    :param who:
    :param age:
    :return:
    """
    print("Hello,every one!")
    time.sleep(10)
    print("%s is %s cm!" % (who, ht))
    
def print_bcd(who, bcd):
    """
    需要用多线程调用的函数
    :param who:
    :param age:
    :return:
    """
    print("Hello,every one!")
    time.sleep(15)
    print("%s is %s nm!" % (who, bcd))
    
if __name__ == "__main__":
    
    time0 = time.time()
    print_age("jack", 18)
    print_bcd("bcd", 25)
    print_ht("ht", 175)
    
    time1 = time.time()
    print(time1 - time0, "s")

结果如下:

Hello,every one!
jack is 18 years old !
Hello,every one!
bcd is 25 nm!
Hello,every one!
ht is 175 cm!
30.018718957901 s

而多线程处理的话,如下:

import threading
import time

def print_age(who, age):
    """
    需要用多线程调用的函数
    :param who:
    :param age:
    :return:
    """
    print("Hello,every one!")
    time.sleep(5)
    print("%s is %s years old !" % (who, age))

def print_ht(who, ht):
    """
    需要用多线程调用的函数
    :param who:
    :param age:
    :return:
    """
    print("Hello,every one!")
    time.sleep(10)
    print("%s is %s cm!" % (who, ht))
    
def print_bcd(who, bcd):
    """
    需要用多线程调用的函数
    :param who:
    :param age:
    :return:
    """
    print("Hello,every one!")
    time.sleep(15)
    print("%s is %s nm!" % (who, bcd))
    
if __name__ == "__main__":
    
    time0 = time.time()
    t1 = threading.Thread(target = print_age, args=("jack", 18, ))     # 创建线程1
    t2 = threading.Thread(target = print_bcd, args=("bcd", 25, ))    # 创建线程2
    t3 = threading.Thread(target = print_ht, args=("ht", 175,))     # 创建线程3
    t1.start()    # 运行线程1
    t2.start()    # 运行线程2
    t3.start()    # 运行线程3
    t1.join()
    t2.join()
    t3.join()
    
    time1 = time.time()
    print(time1 - time0, "s")

结果如下:

Hello,every one!Hello,every one!

Hello,every one!
jack is 18 years old !
ht is 175 cm!
bcd is 25 nm!
15.031706809997559 s

第一,从时间上可以直观地看到,多线程处理的结果的时间比一步一步处理的时间要短。

第二,如果是多个输出的任务的话,可以交给多线程并行处理,可以提高程序的效率。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值