2018-09-13day19-多线程

2018-09-13  本文已影响0人  猫爱老鼠丶

一、多线程技术

1.主线程

每个进程默认都会有一个线程,这个线程我们一般叫它主线程
默认情况下,所有的代码都是在主线程中执行

2.子线程

一个线程中可以有多个线程。除了主线程以外,其他的线程需要手动添加

3.threading是python中的一个内置模块,用来支持多线程

import threading
import datetime
import time
# 下载两个电影
def download(file):
    print('开始下载:', datetime.datetime.now())
    print(threading.currentThread())
    # 让线程阻塞5秒
    time.sleep(5)
    print(file+'下载结束',datetime.datetime.now())

print('主线程中的代码')
print(threading.currentThread())

Thread(target,args)
target:需要在子线程中调用的函数的函数名
args:函数的实参
返回值:创建好的线程对象
"""
t1 = threading.Thread(target=download, args=('终结者2',))
# 开始执行t1对应的线程中的任务
t1.start()

运行结果:
主线程中的代码
<_MainThread(MainThread, started 2692)>
开始下载: 2018-09-13 17:18:38.315052
<Thread(Thread-1, started 1064)>
终结者2下载结束 2018-09-13 17:18:43.319062

二、面向对象的多线程技术

面向对象实现多线程

1.声明一个类继承自Thread类
2.重写run方法,将需要在子线程中执行的任务放到run方法中
3.再需要子线程的位置去创建这个类的对象,然后用对象调用start方法去执行run中的任务

class DownloadTread(Thread):
    def __init__(self, file):
        super().__init__()
        self.file = file
    def run(self):
        print(self.file+'开始下载:', datetime.datetime.now())
        time.sleep(randint(5,10))
        print('下载结束:', datetime.datetime.now())

t1 = DownloadTread('辛德勒的名单')
t1.start()
print('=========================下载中======================')

运行结果:
辛德勒的名单开始下载: 2018-09-13 17:21:05.806199
=========================下载中======================
下载结束: 2018-09-13 17:21:15.807142

三、join方法的使用

如果希望某个线程结束后才执行某个操作,就用那个线程调用join方法
使用方法:线程对象.join()

四、线程间的数据共享

模拟多个人对用一个账号进行操作

"""__author__ = 唐宏进 """
from threading import Thread,Lock
import time
"""
模拟多个人对同一个账号进行操作

同步锁(RLock)和互斥锁(Lock)
"""

class Account:
    """账号类"""
    def __init__(self, balance):
        # 余额
        self.balance = balance
        # 创建锁对象
        self.lock = Lock()

    # 存钱的过程:读出原来的余额,确定钱一系列操作,将原来的余额加上存的数额产生最新的余额保存
    def save_money(self, amount):
        """存钱"""
        print('开始存钱')
        # 加锁
        self.lock.acquire()
        # 获取原来的余额
        old_amount = self.balance
        # 模拟时间消耗
        time.sleep(5)
        self.balance = old_amount + amount
        print('存钱成功!最新余额:',self.balance)
        # 解锁
        self.lock.release()

    def take_money(self, amount):
        """取钱"""
        print('开始取钱')
        # 加锁
        self.lock.acquire()

        old_amount = self.balance
        if amount > old_amount:
            print('余额不足!')
            return
        time.sleep(5)
        self.balance = self.balance - amount
        print('取钱成功!最新余额:',self.balance)
        # 解锁
        self.lock.release()

    def show_balance(self):
        print('当前余额为:',self.balance)


# 创建账号
# p1 = Account(1000)
# p1.save_money(200)
# p1.take_money(100)
# p1.show_balance()

"""
当多个线程同时对一个数据进行操作的时候,可能会出现数据混乱的问题
"""
p1 = Account(1000)
t1 = Thread(target=p1.save_money, args=(200,))
t2 = Thread(target=p1.save_money, args=(100,))
t3 = Thread(target=p1.take_money, args=(500,))
t1.start()
t2.start()
t3.start()

t1.join()
t2.join()
t3.join()
p1.show_balance()

运行结果:
开始存钱
开始存钱
开始取钱
存钱成功!最新余额: 1200
存钱成功!最新余额: 1300
取钱成功!最新余额: 800
当前余额为: 800
上一篇下一篇

猜你喜欢

热点阅读