1. 创建多线程对象
有两种方法可以创建线程对象:
(1)直接实例化
thread1 = threading.Thread(target=get_detail_html, args=("", ))
thread2 = threading.Thread(target=get_detail_url, args=("", ))
thread1.start()
thread2.start()
(2)通过继承 threading.Thread 来实现多线程编程,需要重载 run() 方法
class GetDetailHtml(threading.Thread):
def __init__(self, name):
super().__init__(name=name)
def run(self):
print("get detail html started")
time.sleep(2)
print("get detail html end")
class GetDetailUrl(threading.Thread):
def __init__(self, name):
super().__init__(name=name)
def run(self):
print("get detail url started")
time.sleep(4)
print("get detail url end")
thread1 = GetDetailHtml("get_detail_html")
thread2 = GetDetailUrl("get_detail_url")
thread1.start()
thread2.start()
2. 设置子线程阻塞
上面的代码没有设置线程阻塞,如果想在子线程 thread1 和 thread2 跑完后,再接着跑主线程的代码,可以用.join()方法。
thread1.start()
thread2.start()
# 在thread.start() 之后,设置thread.join()
# .join()方法使当前线程终止之后才能从thread.join()返回
thread1.join()
thread2.join()
3.设置守护线程
将子线程设置为守护线程,可以在主线程退出时, 也强制把子线程关闭
thread1.setDaemon(True)
thread2.setDaemon(True)
将两个子线程设置为守护线程,当主线程退出时,会把守护线程的子线程kill掉。