线程回顾 ----多线程爬虫
import threading
def run(a):
#当前线程
c = threading.current_thread()
print('子线程开始',c.name)
#创建一个线程
t = threading.Thread( target = run,args=(1,),name='haha')
#启动线程
t.start()
#关闭线程
t.join()
#基于类的线程
#实例:
import threading
import time
# 写一个类,继承自threading.Thread
# main else
class SingThread(threading.Thread):
def __init__(self, name, a):
super().__init__()
self.name = name
self.a = a
def run(self):
print('线程名字是%s,接受的参数是%s' % (self.name, self.a))
for x in range(1, 6):
print('我在唱七里香')
time.sleep(1)
class DanceThread(threading.Thread):
def __init__(self, name, a):
super().__init__()
self.name = name
self.a = a
def run(self):
print('线程名字是%s,接受的参数是%s' % (self.name, self.a))
for x in range(1, 6):
print('我在跳广场舞')
time.sleep(1)
def main():
# 创建线程
tsing = SingThread('sing', '猪八戒')
tdance = DanceThread('dance', '猪悟能')
# 启动线程
tsing.start()
tdance.start()
# 让主线程等待结束
tsing.join()
tdance.join()
print('主线程和子线程全部结束')
if __name__ == '__main__':
main()