一、多線程
每個程序在運行的時候系統(tǒng)都會為這個進程創(chuàng)建一個線程,這個線程我們叫主線程
程序員自己創(chuàng)建除線程我們叫子線程
程序員自己創(chuàng)建的線程叫子線程
多個任務在一個線程中按順序一個一個執(zhí)行的(線程的串行)
多個線程的任務同時執(zhí)行
import time
import datetime
from random import randint
import threading
def download(file):
print(datetime.datetime.now(), '開始下載,%s' % file)
# sleep(時間):將當前線程阻塞指定的時間
# 時間單位:秒
time.sleep(randint(5, 10))
print(datetime.datetime.now(), '下載%s結(jié)束' % file)
"""
python通過threading標準庫來支持多線程
"""
if __name__ == '__main__':
"""
Thread(target= , args=)
target : 傳一個需要在子線程中執(zhí)行函數(shù)(類型是function的變量)
args: 在子線程中調(diào)用target對應函數(shù)的時候,該傳什么參數(shù)
"""
# current_thread()獲取當前線程
t1 = threading.Thread(target=download, args=('阿甘正傳',))
t1.start()
t2 = threading.Thread(target=download, args=('救贖',))
t2.start()
二、創(chuàng)建進程的方式
創(chuàng)建線程方式1:
直接通過Thread類創(chuàng)建對象,將需要在子線程中執(zhí)行的函數(shù)作為target參數(shù)穿進去
創(chuàng)建線程方式2:
a.自己寫一個類去繼承Thrad類
b.重寫實現(xiàn)類的run方法,run中的任務就是在子線程中執(zhí)行的任務
c.創(chuàng)建當前類的對象,就是線程對象.然后調(diào)用start去執(zhí)行線程中任務
from threading import Thread
import datetime
from time import sleep
# 創(chuàng)建線程類
class DownLoadThread(Thread):
"""下載線程類"""
def __init__(self, file):
super().__init__()
self.file = file
def run(self):
print('%s開始下載, ' % self.file, datetime.datetime.now())
sleep(5)
print('%s下載結(jié)束, ' % self.file, datetime.datetime.now())
# 創(chuàng)建線程對象
t1 = DownLoadThread('火影忍者')
t2 = DownLoadThread('進擊的巨人')
# 通過start去執(zhí)行run中任務
t1.start()
t2.start()
三、多線程的服務器與客戶端
服務器代碼
import socket
from threading import Thread
class Onlien(Thread):
def __init__(self, conversation: socket.socket, add):
super().__init__()
self.conversation = conversation
self.add = add
def run(self):
while True:
message_re = self.conversation.recv(1024).decode('utf-8')
print(self.add[0], ':', message_re)
self.conversation.send('你好!你好'.encode('utf-8'))
def creat_server():
server = socket.socket()
server.bind(('10.7.156.86', 8080))
server.listen(512)
while True:
conversation, add = server.accept()
# 創(chuàng)建處理這個請求對應的子線程
t = Onlien(conversation, add)
t.start()
if __name__ == '__main__':
creat_server()
客戶端代碼
import socket
client = socket.socket()
client.connect(('10.7.156.97', 8081))
while True:
message = input('>>>')
client.send(message.encode('utf-8'))
print(client.recv(1024).decode())