一.多線程
python 內(nèi)置的threading 模塊 可以支持多線程
所有的進(jìn)程默認(rèn)都有一個(gè)線程(一般叫這個(gè)線程為主線程)其他的線程叫子線程
如果想要在進(jìn)程中添加其他對象 就創(chuàng)建線程對象
import threading
import time
def download(file):
print('開始下載',file)
time.sleep(5)
print(file,'下載結(jié)束')
if __name__ == '__main__':
print('abc')
#1.創(chuàng)建線程對象
"""
target;需要在子線程執(zhí)行的函數(shù)
args:調(diào)用函數(shù)的實(shí)參列表(參數(shù)類型是列表)
返回值:線程對象
"""
t1=threading.Thread(target=download,args=['愛情公寓'])
#2.在子線程執(zhí)行任務(wù)
t1.start()
t2 = threading.Thread(target=download, args=['狄仁杰'])
t2.start()
# download('愛情')
# download('狄仁杰')
print('=======')
import threading
import time
def download(file,time1):
print('開始下載',file)
time.sleep(time1)
print(file,'下載結(jié)束')
if __name__ == '__main__':
print('abc')
#1.創(chuàng)建線程對象
"""
target;需要在子線程執(zhí)行的函數(shù)
args:調(diào)用函數(shù)的實(shí)參列表(參數(shù)類型是列表)
返回值:線程對象
"""
t1=threading.Thread(target=download,args=['愛情公寓',10])
#2.在子線程執(zhí)行任務(wù)
t1.start()
t2 = threading.Thread(target=download, args=['狄仁杰',5])
t2.start()
# download('愛情')
# download('狄仁杰')
print('=======')
t3=threading.Thread()
value=input('>>>>')
print('!!!!!!')
二.
# from threading import Thread
# import requests
# """
# 方式2:寫一個(gè)自己的線程類
# 1.下一個(gè)類 繼承自Thread類
# 2.重寫run方法在里面規(guī)定需要在子線程中執(zhí)行的任務(wù)
# 3.實(shí)現(xiàn)在子線程中執(zhí)行的任務(wù)對應(yīng)的功能 如果需要參數(shù),通過類的屬性來傳值
# """
# #下載數(shù)據(jù)
# class DownloadThread(Thread):
# def run(self):
# """run方法"""
# """
# 寫這個(gè)方法的內(nèi)容就是在子線程中執(zhí)行的內(nèi)容
# 這個(gè)方法不要直接調(diào)用
#
# """
# print('開始下載')
# response=requests.request('GET','http://10.7.181.117/shareX/Git.exe')
# data=response.content
# with open('./git.exe','wb')as f:
# f.write(data)
# print('下載完成')
#
#
#
# if __name__ == '__main__':
# print('=======')
# t1=DownloadThread()
# #通過start簡介調(diào)用run方法 run方法中賦任務(wù)在子線程中執(zhí)行
# t1.start()
# #直接調(diào)用run方法,run方法的任務(wù)在當(dāng)前線程中執(zhí)行。。、
# print('!!!!!!!')
from threading import Thread
import requests
import re
# 下載數(shù)據(jù)
class DownloadThread(Thread):
def __init__(self,file_path):
super().__init__()
self.file_path=file_path
def run(self):
print('開始下載')
response = requests.request('GET', self.file_path)
data = response.content
#獲取文件后綴
# suffix = re.findall(r'([^%/]+\.[a-zA-Z]+)$', self.file_path)[0] #方法二
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')
t1.start()
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('!!!!!!!')
三.多線程的應(yīng)用
服務(wù)端
"""___luopeng___"""
from threading import Thread
import socket
class ConversationThread(Thread):
"""在子線程中處理不同的客戶端會話"""
"""
python中可以在函數(shù)參數(shù)后面加一個(gè)冒號 來對參數(shù)的類型進(jìn)行說明
"""
def __init__(self,conversation,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.103',8001))
server.listen(512)
while True:
conversation,address=server.accept()
t=ConversationThread(conversation,address)
t.start()
# while True:
#
# conversation.send('abc'.encode())
# print(conversation.recv(1024).decode(encoding='utf-8'))
客戶端
"""___luopeng___"""
import socket
if __name__ == '__main__':
client=socket.socket()
client.connect(('10.7.181.117',8080))
while True:
print(client.recv(1024).decode(encoding='utf-8'))
message=input('>>>>>')
client.send(message.encode())
四 join 函數(shù)
"""___luopeng___"""
from threading import Thread
import time
from random import randint
class Download(Thread):
def __init__(self,file):
#這兒的父類的init方法必須調(diào)用,否則當(dāng)前這個(gè)創(chuàng)建的對象中就沒有新的線程
super().__init__()
self.file=file
def run(self):
print('開始下載:%s'% self.file)
time.sleep(randint(5,10))
print('%s下載結(jié)束'% self.file)
if __name__ == '__main__':
#time.time():獲取當(dāng)前時(shí)間—時(shí)間戳
start_time=time.time()
t1=Download('最強(qiáng)Z')
t1.start()
t2=Download('最強(qiáng) A')
t2.start()
print('====')
# print(currentTread())
#如果一個(gè)任務(wù)想要在另外一個(gè)子線程中的任務(wù)執(zhí)行完成后再執(zhí)行,
# 就在當(dāng)前任務(wù)前用子線程對象調(diào)用join方法
#join也會阻塞線程 阻塞到對應(yīng)的子線程中任務(wù)執(zhí)行完為止
t1.join()
#t2.join()
end_time=time.time()
print('總時(shí)間:%.2f'%(end_time - start_time))