Python 35 线程(1)线程理论、开启线程的两种方式

时间:2023-03-10 03:31:50
Python 35 线程(1)线程理论、开启线程的两种方式

一:线程理论

1 什么是线程

进程其实一个资源单位,而进程内的线程才是cpu上的执行单位

线程其实指的就是代码的执行过程
2 为何要用线程
   线程vs进程
     1. 同一进程下的多个线程共享该进程内的资源
     2. 创建线程的开销要远远小于进程
3 如何用线程

二:开启线程的两种方式

1、Thread类的用法

Thread实例对象的方法
# isAlive(): 返回线程是否活动的。
# getName(): 返回线程名。
# setName(): 设置线程名。 threading模块提供的一些方法:
# threading.currentThread(): 返回当前的线程变量。
# threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
# threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

2、开启线程的两种方式:

#开启线程的方式一:
from threading import Thread
import time def task(name):
print('%s is running' %name)
time.sleep(2)
print('%s is done' %name) if __name__ == '__main__':
t=Thread(target=task,args=('线程1',))
t.start()
print('主')

开启线程的方式一:

#开启线程的方式二:
from threading import Thread
import time class Mythread(Thread):
def run(self):
print('%s is running' %self.name)
time.sleep(2)
print('%s is done' %self.name) if __name__ == '__main__':
t=Mythread()
t.start()
print('主')

开启线程的方式二: