昨天运用多进程爬取豆瓣TOP250 影片评分等信息,今天来复习 线程。
- 可以参考Python 官方对线程的理解 线程是一种对于非顺序依赖的多个任务进行解耦的技术。
- 今天主要复习线程的继承和线程间的通信
- 线程的继承,示例如下:
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退出了
退出主进程
好了,今天到这里吧 明天再复习线程的优先级。
加油 !晚安