DAY19 thread线程2018-07-05

01-thread 线程

02-threadClass 线程类

03-joinFunction函数

04-multipleThreadsShareData多线程共享数据


01-thread 线程

主线程:每个python程序,在运行的时候,系统都默认为这个进程创建一个线程来执行程序
子线程:如果想要程序不在主线程中执行,就需要手动的去创建其他的线程-->threading模块(python内置的模块)

time模块是python内置的时间相关的模块,里面提供了很多时间相关的类和方法

import time
import threading


def download(file):
    print('开始下载%s...' % file)
    time.sleep(5)       # 阻止线程运行,时间为10秒
    print('%s下载完成,耗时5秒' % file)


if __name__ == '__main__':

========在主线程中下载两个内容============

    # 获取当前时间
    # start = time.time()
    # download('一人之下.mp4')
    # download('hai_ze_wang.mov')
    # end = time.time()
    # print('共耗时:%d秒' % (end-start))

==========创建新线程=========

    # 1.创建线程对象
    """
    target:需要在当前创建的子线程中执行的函数(函数变量)
    args:给需要在子线程中执行的函数的参数(元组) -->注意,实参后必须加逗号
    """
    t1 = threading.Thread(target=download, args=('一人之下.mp4',))

    # 2.执行需要在子线程中执行的代码
    t1.start()

    t2 = threading.Thread(target=download, args=('hai',))
    t2.start()

    print('second task.')

02-threadClass 线程类

from threading import Thread
import time

1.1.声明一个类,继承自Thread

class DownloadThread(Thread):
     # 5.重写init方法来接收,run中需要的外部的内容
    def __init__(self, file):
        # 必须调用父类的init方法
        super().__init__()
        self.file = file

    # 2.重写run方法(run方法中的代码就是在子线程中执行的代码)
    def run(self):
        print('This word is print in the child thread!')

        print('start download %s' % self.file)
        time.sleep(5)
        print('%s download finish!' % self.file)



if __name__ == "__main__":

1.3.通过Thread的子类去创建对象

t1 = DownloadThread('aa.mp4')

1.4.调用start方法,执行子线程中的任务(不能直接调用run方法)

# t1.run()        # 直接调用run(),run中的代码是在当前线程中执行的
t1.start()      #通过start间接调用run,run中的代码是在新的线程中执行

print('continue print==============')
t2 = DownloadThread('HUO.MP4')
t2.start()

03-joinFunction join函数

from threading import Thread
import time


# 写代码,计算1~n(n>1000000)的和(在子线程中完成)
class Sum(Thread):
    """线程类--计算大数据的和"""
    def __init__(self, n):
        super().__init__()
        self.n = n
        self.result = None

    def run(self):
        time.sleep(3)
        sum1 = 0
        for x in range(1, self.n+1):
            sum1 += x
        self.result = sum1


if __name__ == '__main__':
    t1 = Sum(10000000)
    t1.start()
    print('======')

在t1线程的任务执行完成后才去执行,后面的代码
注意:join会阻塞线程,如果想要在一个子线程中的代码执行完后才执行的代码,要放到当前线程的最后面

    t1.join()
    print(t1.result)

04-multipleThreadsShareData多线程共享数据

一个银行账号,可以通过银行柜台存取钱、可以通过支付宝存取钱、可以通过微信存取钱....
存钱:拿到余额数量 ---耗时---->余额数+存进去的数量---->将最新的余额存进系统

多个线程同时对一个数据进行读写操作,会出现数据错乱的问题--->解决方案:加锁Lock
注意:加锁是给数据加锁,获取锁--lock.acquire();释放锁--lock.release()

from threading import Thread, Lock, RLock
import time

class Account:
    def __init__(self, balance):
        self.name = ''
        self.user_id = ''
        self.balance = balance
        # 1.给数据加锁
        self.lock = Lock()


class SaveMoneyThread(Thread):
    def __init__(self, account, count):
        super().__init__()
        self.account = account
        self.count = count

    def run(self):
        # 在数据读出来到写进去之间加锁
        # 2.获取锁(加锁)
        self.account.lock.acquire()
        # 取出余额
        money = self.account.balance
        # 等待一段时间
        time.sleep(1)
        # 将钱存进入
        self.account.balance = money + self.count
        # 3.释放锁(解锁)
        self.account.lock.release()
        print('=====')


if __name__ == '__main__':
    account = Account(1000)
    account.name = '余婷'

    # 通过10个子线程,对同一个数据进行操作
    threads = []
    for _ in range(10):
        t = SaveMoneyThread(account, 100)
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

    # time.sleep(10)

    print(account.balance)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 进程和线程 进程 所有运行中的任务通常对应一个进程,当一个程序进入内存运行时,即变成一个进程.进程是处于运行过程中...
    小徐andorid阅读 7,886评论 3 53
  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 9,707评论 4 16
  • 线程 引言&动机 考虑一下这个场景,我们有10000条数据需要处理,处理每条数据需要花费1秒,但读取数据只需要0....
    不浪漫的浪漫_ea03阅读 2,924评论 0 0
  • 引言&动机 考虑一下这个场景,我们有10000条数据需要处理,处理每条数据需要花费1秒,但读取数据只需要0.1秒,...
    chen_000阅读 3,532评论 0 0
  • 那一刻,我升起风马,不为乞福,只为守候你的到来; 那一天,闭目在经殿香雾中,蓦然听见,你诵经中的真言; 那一月,我...
    仲夏流萤阅读 3,733评论 8 15

友情链接更多精彩内容