(一)函数+类
14、多线程编程(并发)定义
多线程会为线程取名Thread-1,Thread-2
import threading
import time
from threading import current_thread
def myThread(arg1,arg2):
print(current_thread().getName(),'start')#current_thread获取线程名称
print('%s %s'%(arg1,arg2))
time.sleep(1)#为了能看到运行过程,休眠1秒
print(current_thread().getName(), 'stop')
for i in range(1,6,1):
t1=threading.Thread(target=myThread,args=(i,i+1))
t1.start()#线程启动,实际调用了run()方法
print(current_thread().getName(),'end!')#输出主线程什么时候结束
由上图输出我们发现,线程们是并行执行的,主线程先结束后,其他线程(1-5)才结束。如果我们想要线程间有依赖关系,就是让1-5先结束,再结束主线程-----依赖关系即线程间的同步。
使用面向对象的方法,再写一遍:
注:
- 运用多态知识,把run()进行重写;
- Mythread继承了threading.Thread;
- 为什么要写from threading import current_thread?因为名称比较长,如果不这样引入,后面使用时需要threading.current_thread。
#面向对象
import threading
from threading import current_thread
class Mythread(threading.Thread):
def run(self):
print(current_thread().getName(),'start')
print('run!')
print(current_thread().getName(),'stop')
t1 = Mythread()
t1.start()#运行
t1.join()#?
print(current_thread().getName(),'end')
输出结果是:
Join()方法
可以看到使用面向对象我们实现了需求,但是这里出现了join() 方法,这个方法有何意义呢?其实它就 保证了不会出现前例中主线程先结束的现象,他是用来确定线程何时结束。我们再添加进一个线程试验以下:
t1 = Mythread()
t1.start()
t1.join()
t2 = Mythread()
t2.start()
print(current_thread().getName(),'end')
由上输出结果看到
t1有join()方法,t1结束,主线程结束,然后t2结束了,再看另一个例子:
t1 = Mythread()
t1.start()
t2 = Mythread()
t2.start()
t2.join()
print(current_thread().getName(),'end')
我们给t2有join()方法,所以直到t2结束,主线程才结束。
由以上推出:
join方法的作用就是,调用它的线程终止,则主线程终止;
就好比join是容器,其中的线程结束,容器结束,主线程也被带走,容器外的该干啥干啥
因为:每个线程都是独立的个体
15、生产者消费者问题
未完…
16、Python正则表达式库re
所有正则表达式操作都使用 python 标准库中的 re 模块。
学习链接:https://docs.python.org/zh-cn/3.6/library/re.html#regular-expression-examples
python 正则表达式详解
元字符: