美文网首页
DAY19 thread线程2018-07-05

DAY19 thread线程2018-07-05

作者: 十二右 | 来源:发表于2018-07-07 11:26 被阅读0次

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)

相关文章

  • DAY19 thread线程2018-07-05

    01-thread 线程 02-threadClass 线程类 03-joinFunction函数 04-mult...

  • 线程协程WWW

    线程:Thread // 新线程-1 调用静态方法 Thread m_Thread_1 = new Thread(...

  • Thread

    线程机制理解开启线程: Thread thread = new Thread(Runnable).start();...

  • 守护线程(Daemon)

    线程分类 User Thread(用户线程) Daemon Thread(守护线程) 定义: 守护线程--也称“服...

  • 多线程

    Java多线程----Thread java使用Thread类代表线程,所有的线程对象必须是Thread类或者其子...

  • 守护线程

    在Java中有两类线程:用户线程 (User Thread)、守护线程 (Daemon Thread)。 守护线程...

  • 守护线程(Daemon Thread)

    守护线程(Daemon Thread) 在Java中有两类线程:用户线程 (User Thread)、守护线程 (...

  • Java并发编程(4):守护线程与线程阻塞的四种情况

    守护线程 Java中有两类线程:User Thread(用户线程)、Daemon Thread(守护线程) 用户线...

  • java线程分类

    守护线程 java中有两类线程,用户线程(User Thread)和守护线程(Daemon Thread)。 守护...

  • 异步和线程池

    四种方式创建线程 1.通过Thread类创建线程 Thread01 thread = new Thread01()...

网友评论

      本文标题:DAY19 thread线程2018-07-05

      本文链接:https://www.haomeiwen.com/subject/pwaiuftx.html