基本概念:
进程:独立的所有子任务的集合
线程:进程中的每个子任务,不能独立存在
线程,进程:都是想同时完成多个任务
特点:
进程的特点:独立(内存独立,cpu使用独立)启动进程开销大(速率低),进程之间很难共享数据和数据通信,数据安全高
线程的特点:依赖进程(内存共享,cpu使用独立)启动开销小,线程之间共享数据容易,方便通信,线程不安全。python3
python3 模拟线程:
单线程:
用函数实现线程,实例:
import threading,time
def Thread():
for i in range(11):
print(i)
time.sleep(1) #让cpu休息一秒
threading._start_new_thread(Thread,()) #不会马上运行,主线程结束,他就马上结束,因为线程它不可以独立存在
print("主线程")
input() #有了这个input()主线程就不会马上结束 ,除非你输入内容
用类方式实现线程:(实例)
import threading,time
class mythread(threading.Thread): #继承了threading.Thread这个类
def
__init__(self):
threading.Thread.__init__(self)
print("mythread……")
def run(self): #重写run方法
for
i in range(11):
print(i)
time.sleep(1)
def start(self): #重写start方法
print("start……")
super().start()
#只有父类的start方法才能启动你的run方法,因为你的start方法没有实现启动run方法的功能
t=mythread()
t.start()
threading模块除了包含Thread模块中所有的方法外,还提供了其他方法,比如:
threading.currentThread(): 返回当前的线程变量
threading.enumerate():返回一个包含正在运行的线程的list.正在运行指启动后,结束前,不包括未开始或以结束的线程。
threading.activeCount():返回当前运行线程的数量,与len(threading.enumerate())有相同的结果
Thread这个类提供了以下方法:
run():用来表示线程活动的方法
start():启动线程活动, 或启动run方法
join([time]):等待至线程终止。这阻塞调用线程直至线程的join()方法调用被终止-正常退出或抛出未处理的异常-或者是
可选的超时发生。 默认为本线程运行结束,或出现异常终止,再执行其他线程。
线程的状态类型:
1.新建状态:新创建了一个线程对象
2.就绪状态:线程对象创建后,其他线程调用了该对象的start()方法,该线程变的可运行进入线程池中等待获取cpu的使用
权。
3.运行状态:就绪状态的线程获取了cpu,正在执行改代码程序
4.阻塞状态:线程因为某中原因放弃cpu的使用权,就绪状态的线程才有机会转到运行状态。
5.死亡状态:线程执行完了或者因异常退出了run()方法,该线程结束生命周期。