"""
开设线程不需要在main方法下面,但是习惯将其写在main方法下
同一个进程下的线程,会共享该进程下的全局数据
先开启的进程,未必先结束
"""
from threading import Thread, active_count, current_thread
import time
def task(name):
print(f'{name} is start')
time.sleep(0.1)
print(f'{name} is over')
if __name__ == '__main__':
t = Thread(target=task, args=('苏轼', ))
t.start()
# 主线程等待子线程运行完毕才会运行
t.join()
print('it is main')
# 创建线程的速度高于进程,因此在主线程前的代码会优先执行
# 苏轼 is start
# it is main
# 苏轼 is over
class MyThread(Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
# 当前线程的名字
print(f'{self.name} is start')
time.sleep(1)
print(f'{self.name} is over')
if __name__ == '__main__':
t = MyThread('李白')
t.start()
# 获取当前线程的名字
print(current_thread().name)
# MainThread
# 统计当前正在活跃的线程数
print(active_count())
# 2
from threading import Thread
import time
def task(name):
print(f'{name} is start')
time.sleep(0.1)
print(f'{name} is over')
if __name__ == '__main__':
t = Thread(target=task, args=('苏轼', ))
# 将线程设置为守护线程
# 当主线程关闭后,守护线程随之关闭
t.daemon = True
t.start()
print('it is main')
# 苏轼 is start
# it is main