python求职准备第3天—线程

 

   昨天运用多进程爬取豆瓣TOP250 影片评分等信息,今天来复习 线程。

 

  • 可以参考Python 官方对线程的理解  线程是一种对于非顺序依赖的多个任务进行解耦的技术。
  • 今天主要复习线程的继承和线程间的通信
  1. 线程的继承,示例如下:
from threading import Thread
import time
from random import randint


class MyThread(Thread):
    def __init__(self,id,name):
        super(MyThread,self).__init__()
        self.id =id
        self.name =name

    def run(self):
        print(f'{self.name}正在运行')
        sleep_time = randint(1,10)
        time.sleep(sleep_time)
        print(f'{self.name}运行{sleep_time}秒了后退出')

def main():

    thread1 = MyThread(1,'线程1')
    thread2 = MyThread(2,'线程2')

    thread1.start()
    thread2.start()
    
    thread1.join()
    thread2.join()
    print('退出主进程')

if __name__ == '__main__':
    main()

     运行结果如下:

线程1正在运行
线程2正在运行
线程2运行4秒了后退出
线程1运行9秒了后退出
退出主进程

 

    2.复习一下 线程之间的同步

  Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,可以将其操作放到 acquire 和 release 方法之间,示例如下: 

import threading
import time
from random import randint


class MyThread(threading.Thread):

    def __init__(self,id,name):
        super(MyThread,self).__init__()
        self.id = id
        self.name = name
        self.count = 0

    def run(self):

        threadLock = threading.Lock()

        print(f'开启{self.name}')

        #开启线程同步
        threadLock.acquire()
        self.task(3)
        #释放线程
        threadLock.release()

        print(f'{self.name}退出了')


    def task(self,counter):
        while counter:
            time.sleep(randint(1,3))
            print(f'{self.name}正在运行中')
            counter -= 1



def main():

    thread1 = MyThread(1,'线程1')
    thread2 = MyThread(2,'线程2')

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()
    print('退出主进程')

if __name__ == '__main__':
    main()

运行结果如下:

开启线程1
开启线程2
线程1正在运行中
线程1正在运行中
线程2正在运行中
线程1正在运行中
线程1退出了
线程2正在运行中
线程2正在运行中
线程2退出了
退出主进程

 好了,今天到这里吧   明天再复习线程的优先级。

加油 !晚安

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你个闲王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值