自己写的一个比较好用的线程等待代码模板,python3环境下
我的应用场景:在拨号爬虫的时候,重新拨号之后数据库的连接会出现异常,所以需要用到
简介:A是爬虫线程,B是写控制爬虫线程什么时候停止,然后运行一些其他脚本的线程代码中主要运行逻辑我用的sleep代替
import random
import time
import threading
class A(threading.Thread):
def __init__(self,thread_id,event):
super(A, self).__init__()
self.thread_id=thread_id
self.event=event
self.stopped=False
def run(self):
while 1:
if self.event.is_set():
sleep_time=random.randrange(5,10)
print(self.thread_id,'准备等待:',sleep_time)
time.sleep(sleep_time)
print(self.thread_id,"等待完毕")
else:
self.stopped=True
print(self.thread_id,"线程阻塞,等待中!")
time.sleep(1)
class B(threading.Thread):
def __init__(self,thread_pool):
super(B, self).__init__()
self.thread_pool=thread_p