1. 耗时操作
- 耗时操作放到主线程中的问题:
耗时操作放到主线程中,会阻塞线程
多个耗时操作都放到一个线程中执行,最终执行的时间是两个耗时操作的时间和 - 怎么解决问题?
使用多线程(创建多个线程)
2. 多线程技术1
- python内置的threading模块,可以支持多线程
- 所有的进程默认都有一个线程(一般称为主线程),其他的线程叫子线程
- 如果想要在进程中添加其他的线程,就创建线程对象
import threading
import time
def download(file, time1):
print('开始下载', file)
time.sleep(time1)
print(file, '下载结束')
if __name__ == '__main__':
print('hello')
- 创建线程对象
"""
target:需要在子线程中执行的函数
args:调用函数的实参列表(参数类型是列表)
返回值:线程对象
"""
t1 = threading.Thread(target=download, args=['爱情公寓', 5])
- 在子线程中执行任务
t1.start()
t2 = threading.Thread(target=download, args=['我的兄弟叫顺溜', 3])
t2.start()
# download('天线宝宝')
# download('我的兄弟叫顺溜')
print('============')
运行结果:
hello
开始下载 爱情公寓
开始下载 我的兄弟叫顺溜
============
我的兄弟叫顺溜 下载结束
爱情公寓 下载结束
3. 多线程技术2
方式2:写一个自己的线程类
- 写一个类,继承自Thread类
- 重写run方法,在里面规定需要在子线程中执行的任务
- 实现在子线程中执行任务对应的功能,如果需要参数,通过类的对象属性来传值
from threading import Thread
import requests
import re
# 下载数据
class DownloadThread(Thread):
"""下载类"""
def __init__(self, file_path):
super().__init__()
self.file_path = file_path
def run(self):
"""run方法"""
"""
1. 写在这个方法里面的内容就是在子线程中执行的内容
2. 这个方法不要直接调用
"""
print('开始下载...')
response = requests.request('GET', self.file_path)
data = response.content
# 获取文件后缀
suffix = re.search(r'\.\w+$', self.file_path).group()
with open('./abc'+suffix, 'wb') as f:
f.write(data)
print('下载完成!!!!')
if __name__ == '__main__':
print('哇哈哈哈哈哈哈')
t1 = DownloadThread('http://10.7.181.117/shareX/Git.exe')
# 通过start间接调用run方法,run方法中的任务在子线程中执行
t1.start()
# 直接调用run方法,run方法中的任务在当前线程中执行
# t1.run()
t2 = DownloadThread('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533720058151&di=766b5c97653351e805c85881ecaa57d0&imgtype=0&src=http%3A%2F%2Fx.itunes123.com%2Fuploadfiles%2Fb2ab55461e6dc7a82895c7425fc89017.jpg')
t2.start()
print('呜哇哇哇哇哇哇')
运行结果:
哇哈哈哈哈哈哈
开始下载...
开始下载...
呜哇哇哇哇哇哇
下载完成!!!!
4. 多线程应用
import socket
from threading import Thread
class ConversationThread(Thread):
"""在子线程中处理不同的客户端会话"""
"""
python中可以在函数参数的后面加一个冒号,来对参数的类型进行说明(说明并不是强制转换)
"""
def __init__(self, conversation:socket.socket, address):
super().__init__()
self.conversation = conversation
self.address = address
def run(self):
while True:
self.conversation.send('你好'.encode())
print(self.address, self.conversation.recv(1024).decode(encoding='utf-8'))
if __name__ == '__main__':
server = socket.socket()
server.bind(('10.7.181.93', 8080))
server.listen(10)
while True:
conversation, address = server.accept()
t = ConversationThread(conversation, address)
t.start()
# while True:
# conversation.send('来了啊,小伙子!'.encode())
# print(conversation.recv(1024).decode(encoding='utf-8'))
5. join函数
"""__author__ = Percy"""
from threading import Thread, current_thread
import time
from random import randint
class Download(Thread):
def __init__(self, file):
# 这里父类的init方法必须调用,否则当前这个类创建的对象就没有新的线程
super().__init__()
self.file = file
def run(self):
print(current_thread())
print('%s开始下载了哈...' % self.file)
time.sleep(randint(4, 8))
print('%s下载结束了哈!!!' % self.file)
if __name__ == '__main__':
# time.time():获取当前时间 -- 时间戳
start_time = time.time()
t1 = Download('我的兄弟叫顺溜.mp4')
t1.start()
t2 = Download('黑猫警长.mp4')
t2.start()
print('哇咔咔卡卡卡卡卡')
# 获取当前线程
"""
主线程:MainThread
子线程:Thread-数字(数字从1开始)
"""
print(current_thread())
# 如果一个任务想要在另外一个子线程中的任务执行完成后再执行,就在当前任务前用子线程对象调用join方法
# 所以join也会阻塞线程,阻塞到对应的子线程中任务执行完为止
t1.join()
t2.join()
end_time = time.time()
print('总共消耗时间:%.2f' % (end_time - start_time))
运行结果:
<Download(Thread-1, started 14484)>
我的兄弟叫顺溜.mp4开始下载了哈...
<Download(Thread-2, started 14672)>
黑猫警长.mp4开始下载了哈...
哇咔咔卡卡卡卡卡
<_MainThread(MainThread, started 18356)>
黑猫警长.mp4下载结束了哈!!!
我的兄弟叫顺溜.mp4下载结束了哈!!!
总共消耗时间:8.00