首页 > 编程语言 > 详细

Python-线程

时间:2021-03-13 16:53:51      阅读:35      评论:0      收藏:0      [点我收藏+]

1、threading模块介绍

python的thread模块是比较底层模块,python的threading模块是对thread做一些包装的,可以更加方便被使用
  • 创建线程对象:threading.Thread(target=func1)
  • 参数target指定线程执行的任务(函数)
Thread类提供了以下方法
 
方法
说明
run
用以表示线程活动的方法
start
请的线程活动
join([time])
设置主线程会等待time秒后再往下执行,time默认为子线程结束,多个子线程之间设置的值会叠加
isAlive
返回线程是否活动的
getName
返回线程名
setName
设置线程名
  • threading.current_thread() ==> 返回当前执行的线程
  • threading.enumerate() ==> 返回正在运行的所有线程(list)。正在运行指线程启动后,结束前,不包括启动前和终止后的线程
  • threading.activeCount() ==> 返回正在运行的线程数量

2、多线程实现多任务

技术分享图片
 1 import time
 2 import threading
 3 
 4 
 5 def func1():
 6     for i in range(5):
 7         print("---正在做事情1-----")
 8         time.sleep(1)
 9 
10 
11 def func2():
12     for i in range(6):
13         print("---正在做事情2-----")
14         time.sleep(1)
15 
16 def main():
17     # 创建一个线程执行func1
18     t1 = threading.Thread(target=func1)
19     # 创建一个线程执行func1
20     t2 = threading.Thread(target=func2, name=th_2)
21     s_time = time.time()
22     print(t2.getName())
23     # 开始执行线程1
24     t1.start()
25     # 开始执行线程2
26     t2.start()
27     # 主线程等待子线程执行完后再往下执行
28     t1.join()
29     t2.join()
30     e_time = time.time()
31     print("耗时: ", e_time - s_time)
32 
33 main()
View Code

3、继承Thread类创建线程

技术分享图片
 1 # 通过继承Thread类类创建线程
 2 class RequestThread(threading.Thread):
 3     """发送request请求"""
 4     # 传参数需重写__init__方法(重写后要调用父类__init__方法)
 5     def __init__(self, url):
 6         self.url = url
 7         super().__init__()
 8 
 9     def run(self):
10         res = requests.get(self.url)
11         print("线程:%s ---返回的状态码:%s" % (threading.current_thread(), res.status_code))
12 
13 
14 for i in range(5):
15     t = RequestThread(http://www.baidu.com)
16     t.start()
View Code

 

Python-线程

原文:https://www.cnblogs.com/xi77/p/14529237.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!