day18多线程

2018-08-08  本文已影响0人  KingJX

01-多线程技术

# -*- coding: utf-8 -*-
# @Author: KingJX
# @Date  : 2018/8/8 
import threading
import time

def download(file):
    print('开始下载', file)
    time.sleep(5)
    print(file, '下载结束')

if __name__ == '__main__':
    # 1.创建线程对象
    """
    target: 需要在子线程中执行的函数
    args: 调用函数的实参列表
    返回值是一个线程对象
    """
    thread1 = threading.Thread(target=download, args=['爱情公寓'])

    # 2.在子线程中执行任务
    thread1.start()

    thread2 = threading.Thread(target=download, args=['狄仁杰'])
    thread2.start()
    # download('爱情公寓')
    # download('狄仁杰')

    print('======')

输出结果:
开始下载 爱情公寓
开始下载 狄仁杰
======
狄仁杰 爱情公寓 下载结束
下载结束

02-多线程技术2

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方法"""
        """
        写在这个方法中的内容就是在子线程中执行的内容
        这个方法不要直接调用
        """
        print('开始下载')
        response = requests.request('GET', self.file_path)
        data = response.content
        suffix = re.search(r'\.\w+$', self.file_path).group()

        with open('./git'+suffix, 'wb') as f:
            f.write(data)
        print('下载完成')


if __name__ == '__main__':
    d1 = DownloadThread('http://yuting.local/shareX/Git.exe')

    # 通过start间接调用run方法,run方法中的任务在子线程中执行
    # d1.start()

    d2 = DownloadThread('http://www.sheng-han.com/images/webwxgetmsgimg.jpg')
    d2.start()

03-多线程的应用_1


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('hello'.encode())
            print(self.address, self.conversation.recv(1024).decode(encoding='utf-8'))



if __name__ == '__main__':
    server = socket.socket()
    server.bind(('10.7.181.59', 8080))
    server.listen(512)

    while True:
        conversation, address = server.accept()
        t = ConversationThread(conversation, address)
        t.start()

03-多线程的应用_1

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

    while True:
         daat1 = client.recv(1024)
         print(daat1.decode(encoding='utf-8'))
         message = input('>>>')
         client.send(message.encode())

05-join函数


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

class DownLoad(Thread):
    def __init__(self, file):
        # 这儿父类的init方法必须调用,否则当前这个类创建的对象没有新的线程
        super().__init__()
        self.file = file



    def run(self):

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


if __name__ == '__main__':
    # time.time(): 获取当前时间 - 时间戳
    start_time = time.time()

    t1 = DownLoad('最强Z.mp4')
    t1.start()
    t2 = DownLoad('黄金城.mp4')
    t2.start()
    # 获取当前线程
    """
    主线程: MainThread
    子线程: Thread-数字(数字从1开始)
    """
    print(currentThread())
    # 如果一个操作想要在另外一个子线程中的任务执行完成后再1执行,就在当前任务前用子线程对象调用join()方法
    # 所以join会阻塞线程,阻塞到对应的子线程中的任务执行完为止
    t1.join()
    t2.join()
    end_time = time.time()
    print('总共消耗时间:%.2f' % (end_time - start_time))

上一篇 下一篇

猜你喜欢

热点阅读