1 .线程创建
使用Thread创建
import threading
import time
def a_thread(a):
print("a_thread started")
time.sleep(2)
print("a_thread end")
def b_thread(b):
print("b_thread started")
time.sleep(4)
print("b_thread end")
if __name__ == '__main__':
thread1 = threading.Thread(target=a_thread, args=("",))
thread2 = threading.Thread(target=b_thread, args=("",))
start_time = time.time()
thread1.start()
thread2.start()
print("last time: {}".format(time.time() - start_time))
运行结果
a_thread started
b_thread started
last time: 0.00026798248291015625
a_thread end
b_thread end
需要注意last time很短,是因为时间打印在主线程中,整个例子中a,b,主三个线程并行。所以主线程并没有等待a,b两个线程运行完毕。
继承Thread方式
# 对于io操作 多线程和多进程性能差别不大
# 1. 通过thread实例化
import threading
import time
def a_thread(a):
print("a_thread started")
time.sleep(2)
print("a_thread end")
def b_thread(b):
print("b_thread started")
time.sleep(4)
print("b_thread end")
class A_thread(threading.Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
print("{} started".format(self.name))
time.sleep(2)
print("{} end".format(self.name))
if __name__ == '__main__':
thread1 = A_thread("a_thread")
thread2 = threading.Thread(target=b_thread, args=("",))
# 设置守护线程
# thread2.setDaemon(True)
start_time = time.time()
thread1.start()
thread2.start()
# thread1.join()
# thread2.join()
print("last time: {}".format(time.time() - start_time))
运行结果
a_thread started
b_thread started
last time: 0.0005140304565429688
a_thread end
b_thread end
2.守护线程
上面的例子可以看出main函数主线程走完后,a,b两个线程还在执行
现实场景中可能需要主线程走完,某些子线程就自动关停,如jvm中的gc,当java程序关闭后,gc直接关闭,我们把这种线程称为守护线程(Daemon)
python中实现守护线程比较简单,直接调用setDaemon方法,如下
# 对于io操作 多线程和多进程性能差别不大
# 1. 通过thread实例化
import threading
import time
def a_thread(a):
print("a_thread started")
time.sleep(2)
print("a_thread end")
def b_thread(b):
print("b_thread started")
time.sleep(4)
print("b_thread end")
if __name__ == '__main__':
thread1 = threading.Thread(target=a_thread, args=("",))
thread2 = threading.Thread(target=b_thread, args=("",))
# 设置守护线程
thread2.setDaemon(True)
start_time = time.time()
thread1.start()
thread2.start()
print("last time: {}".format(time.time() - start_time))
运行结果
a_thread started
b_thread started
last time: 0.0003409385681152344
a_thread end
可以看到b线程设置为守护线程后,当主线程运行结束,它也随之结束,没有继续执行。
3. 线程加入到当前线程(join)
同样1中的例子,有时需要在一个线程中等待另外的线程执行后才继续执行,如 例子中主线程等待a,b执行完毕才继续执行,则需要使用join方法
import threading
import time
def a_thread(a):
print("a_thread started")
time.sleep(2)
print("a_thread end")
def b_thread(b):
print("b_thread started")
time.sleep(4)
print("b_thread end")
if __name__ == '__main__':
thread1 = threading.Thread(target=a_thread, args=("",))
thread2 = threading.Thread(target=b_thread, args=("",))
start_time = time.time()
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("last time: {}".format(time.time() - start_time))
运行结果
a_thread started
b_thread started
a_thread end
b_thread end
last time: 4.008444786071777