iOS 多執行緒 NSThread

2021-09-24 08:21:36 字數 1114 閱讀 8977

nsthread *thread = [[nsthread alloc] initwithtarget:self selector:@selector(run) object:nil];

[thread start];

複製**

上述2種建立執行緒方式的優缺點
+ (void)sleepuntildate:(nsdate *)date;

+ (void)sleepfortimeinterval:(nstimeinterval)ti;

複製**

+ (void)exit;注意:一旦執行緒停止(死亡)了,就不能再次開啟任務

資源共享1塊資源可能會被多個執行緒共享,也就是多個執行緒可能會訪問同一塊資源 比如多個執行緒訪問同乙個物件、同乙個變數、同乙個檔案 當多個執行緒訪問同一塊資源時,很容易引發資料錯亂資料安全問題

互斥鎖使用格式@synchronized(鎖物件)注意:鎖定1份**只用1把鎖,用多把鎖是無效的

互斥鎖的優缺點

優點:能有效防止因多執行緒搶奪資源造成的資料安全問題

缺點:需要消耗大量的cpu資源

互斥鎖的使用前提:多條執行緒搶奪同一塊資源

執行緒同步的意思是:多條執行緒在同一條線上執行(按順序地執行任務)

互斥鎖,就是使用了執行緒同步技術

複製**

oc在定義屬性時有nonatomic和atomic兩種選擇

- (void)performselectoronmainthread:(sel)aselector withobject:(id)arg waituntildone:(bool)wait;

- (void)performselector:(sel)aselector onthread:(nsthread *)thr withobject:(id)arg waituntildone:(bool)wait;

複製**

附:我的部落格位址

iOS 多執行緒 NSThread

ibaction startthreadbuttonpressed uibutton sender 建立新的執行緒,執行緒的函式為 startthebackgroundjob.具體的 startthebackgroundjob 函式定義如下.void startthebackgroundjob 在第...

iOS 多執行緒 NSThread

nsthread thread nsthread alloc initwithtarget self selector selector run object nil thread start nsthread mainthread 獲得主線程 bool ismainthread 是否為主執行緒 b...

iOS多執行緒之NSThread

ios多執行緒之nsthread 乙個nsthread物件就代表一條執行緒 1.建立,啟動執行緒 nsthread thread nsthread alloc initwithtarget self selector selector run object nil thread start 主線程相...