线程其他相关用法和守护线程
线程其他相关用法
from threading import Thread,currentThread,enumerate,activeCount
# import threading
import time
# threading.current_thread()
# threading.current_thread()
def task():
print('子线程 start')
time.sleep(2)
print('子线程 end')
print(enumerate())
# print(currentThread(),'子线程')
if __name__ == '__main__':
t1 = Thread(target=task)
t2 = Thread(target=task)
t1.start()
t2.start()
# print(t1.is_alive()) # True
# print(t1.getName()) # Thread-1
# print(t2.getName()) # Thread-2
# t1.setName('班长')
# print(t1.getName())
# print(currentThread().name)
# print(enumerate()) # [<_MainThread(MainThread, started 1856)>, <Thread(Thread-1, started 6948)>, <Thread(Thread-2, started 3128)>]
# print(activeCount()) # 3
# print(len(enumerate())) # 3
守护线程
守护线程:守护的是进程的运行周期
from threading import Thread,enumerate,currentThread
import time
def task():
print('守护线程开始')
print(currentThread())
time.sleep(20)
# print('守护线程结束')
def task2():
print('子线程 start')
time.sleep(5)
print(enumerate())
print('子线程 end')
if __name__ == '__main__':
t1 = Thread(target=task)
t2 = Thread(target=task2)
t1.daemon = True
t2.start()
t1.start()
print('主')