day24-总结

python的多线程

子线程的第一种创建方式

import threading
import time

def download(file):
    print('start', file)
    time.sleep(5)
    print('end', file)

def download1(file):
    print('start', file)
    time.sleep(5)
    print('end', file)

if __name__ == '__main__':
    print('aaa')
    # 1.创建线程对象
    """
    target: 需要在子线程中执行的函数(函数名)
    args: 调用函数的实参列表
    返回值: 线程对象
    """
    new_thread = threading.Thread(target=download, args=['爱情公寓'])
    new_thread2 = threading.Thread(target=download, args=['公寓'])
    # 2.在子线程中执行任务
    new_thread.start()
    new_thread2.start()
    print('------')

子线程的第二张创建方式-对象

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):
        """
        1.写在这个方法的内容就是在子线程中执行的内容
        2.这个方法不要直接调用
        """
        print('开始下载')
        suffix = re.findall(r'([^%/]+\.[a-zA-Z]+)$', self.file_path)[0]
        reponse = requests.request('GET', self.file_path)
        data = reponse.content
        with open('./'+suffix, 'wb') as f:
            f.write(data)
        print('下载完成!')


if __name__ == '__main__':
    print('测试用')
    t1 = 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')
    # 通过start间接调用run方法,run方法中的任务在子线程中执行
    t1.start()
    # 直接调用run方法,直接在当前线程执行
    # t1.run()
    print('下载中......')

多线程的应用-不同的用户端交流

# server.py
import socket
from threading import Thread


class CoversationThread(Thread):
    """在子线程中处理不同的客户端会话"""
    def __init__(self, c, addr):
        super().__init__()
        self.c = c
        self.addr = addr

    def run(self):
        while True:
            try:
                self.c.send('hello'.encode())
                data = self.c.recv(1024)
                print(str(self.addr)+'>>>'+data.decode())
            except ConnectionResetError:
                print(str(self.addr)+' close connection')
                break


if __name__ == '__main__':
    server = socket.socket()
    server.bind(('10.7.181.82', 8080))
    server.listen(512)
    while True:
        c, addr = server.accept()
        client = CoversationThread(c, addr)
        client.start()

# client.py
import socket

if __name__ == '__main__':
    client = socket.socket()
    client.connect(('10.7.181.117', 8080))

    while True:
        print(client.recv(1024).decode())
        message = input('>>>')
        client.send(message.encode())

join函数

from threading import Thread, currentThread
from random import randint
import time


class Download(Thread):

    def __init__(self, file):
        super().__init__()
        self.file = file

    def run(self):
        print(currentThread())
        print('开始下载: %s' % self.file)
        time.sleep(randint(5, 10))
        print('%s下载结束' % self.file)


if __name__ == '__main__':
    # time.time(): 获取当前时间-时间戳
    # currentThread()获取当前线程
    """
    主线程:MainThread
    子线程:Thread-数字(数字从1开始)
    """
    print(currentThread())
    star_time = time.time()
    t1 = Download('最强Z.mp4')
    t1.start()
    t2 = Download('最强Y.mp4')
    t2.start()
    # 如果一个任务想要在另外一个子线程中的任务执行完成后再执行,就在当前任务前用子线程对象调用join方法
    # join也会阻塞线程,阻塞到对应的子线程中的任务执行完为止
    t1.join()
    t2.join()
    end_time = time.time()
    print('总时长:%.2f' % (end_time - star_time))

你可能感兴趣的:(day24-总结)