(一)函數+類
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 正則表達式詳解
元字符: