线程才是真正干活的人
多线程创建:
import threading
import time
def write():
for i in range(10):
print('执行write的线程对象',threading.current_thread())
time.sleep(0.01)
def read():
for i in range(10):
print('执行read的线程对象',threading.current_thread())
time.sleep(0.01)
if __name__ == '__main__':
print('当前程序中,存在的线程列表--------',threading.enumerate())
print('当前存活的线程个数---------------',threading.active_count())
# 创建一个子线程
wh = threading.Thread(target=write)
rh = threading.Thread(target=read)
print('当前程序中,存在的线程列表--------', threading.enumerate())
print('当前存活的线程个数---------------', threading.active_count())
# 开始启动线程
wh.start()
rh.start()
print('当前程序中,存在的线程列表--------', threading.enumerate())
print('当前存活的线程个数---------------', threading.active_count())
# 线程的执行是无序的,由操作系统决定的
注意点:
1、多线程的执行,是无序的,由操作系统来实现
2、多线程的并发操作,节省时间
3、查看当前程序中,运行的线程threading.enumerate,返回的是线程列表, threading.active_count()返回的是线程的个数
重写多线程
import threading
class MyThread(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num =num
def run(self):
print('当前调用run方法')
self.num+=1
print('在当前的线程中,获取的num的数据是',self.num)
if __name__ == '__main__':
t1=MyThread(0)
t2=MyThread(10)
t1.start()
t2.start()#在多线程开发中,全局变量是多个线程都共享的。而局部变量是各自线程的,不能共享
注意点:
1、run方法,不能改名字
2、一般情况下,我们把业务逻辑写在run方法里面
3、start方法用来启动线程,内部确实是直接调用的run方法
4、不能直接使用线程对象调用run方法,因为那样的调用可以实现函数,但是并没有真正的取启动线程
线程的注意点:
线程对于同一个资源的访问,如果没有控制得当,就会对于同一资源的数据进行破坏,而且线程的运行结果不可预料,像这种现象‘线程不安全’
互斥锁解决线程不安全问题,见下篇