併發程式設計 執行緒的使用

2021-10-05 07:56:32 字數 724 閱讀 1643

from threading import thread

from time import sleep

# 執行緒的實現

# 方式一:用方法實現

def func1(name):

print(f"threading: start")

sleep(3)

# 建立執行緒

t1 = thread(target=func1, args=('t1',)) # args 引數需要元組

t2 = thread(target=func1, args=('t2',))

# 開始執行緒

t1.start()

t2.start()

# 方式二:用類來實現

class mythread(thread):

def __init__(self,name):

thread.__init__(self)

self.name = name

def run(self): # 此處規定一定使用run方法,不要自己起名

print(f"threading: start")

sleep(3)

# 建立執行緒

t1 = mythread('t1')

t2 = mythread('t2')

#啟動執行緒

t1.start()

t2.start()

併發程式設計 執行緒的使用

新建狀態 執行new以後,還沒開始執行 就緒狀態 執行了start方法以後,等待cup分配時間執行run方法 執行狀態 執行run方法以後 阻塞狀態 sleep 鎖 阻塞佇列等 死亡狀態 執行完成或報出異常 public class extendscreate extends thread publ...

多執行緒併發程式設計

docker 可謂是開啟了容器化技術的新時代,現在無論大中小公司基本上都對容器化技術有不同程度的嘗試,或是已經進行了大量容器化的改造。伴隨著 kubernetes 和 cloud native 等技術和理念的普及,也大大增加了業務容器化需求。而這一切的推進,不可避免的技術之一便是構建容器映象。在本場...

併發程式設計 守護執行緒

守護執行緒的意思 主程序結束後,不在執行未結束的執行緒了 from threading import thread from time import sleep class mythread thread def init self,name thread.init self self.name n...