標籤:style blog color 使用 strong 檔案
NSThread一.建立和啟動線程1.開線程的幾種方式1)先建立線程,後啟動
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];[thread start];
2)建立線程後自動直接啟動
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];[self performSelectorInBackground:@selector(run) withObject:nil];
3)隱式建立並啟動線程
[self performSelectorInBackground:@selector(run) withObject:nil];
後兩種開線程方法的相比於第一種 的優缺點:
2.其他用法1)主線程相關用法
主線程相關用法+ (NSThread *)mainThread; // 獲得主線程- (BOOL)isMainThread; // 是否為主線程+ (BOOL)isMainThread; // 是否為主線程
2)主線程相關用法
NSThread *current = [NSThread currentThread];//獲得當前線程
3)線程調用的優先順序
+ (double)threadPriority;+ (BOOL)setThreadPriority:(double)p;- (double)threadPriority;- (BOOL)setThreadPriority:(double)p;/*調度優先順序的取值範圍是0.0 ~ 1.0,預設0.5,值越大,優先順序越高*/
4)線程的名字
- (void)setName:(NSString *)n;- (NSString *)name;
二.線程的狀態
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];[thread start];
1.啟動線程
- (void)start;
2. 阻塞(暫停)線程
+ (void)sleepUntilDate:(NSDate *)date;+ (void)sleepForTimeInterval:(NSTimeInterval)ti;// 進入阻塞狀態
3.強制停止線程
+ (void)exit;// 進入死亡狀態
三.多線程的安全隱患1.多安全執行緒隱患
- 一塊資源可能會被多個線程共用,也就是多個線程可能會訪問同一塊資源;
- 比如多個線程訪問同一個對象、同一個變數、同一個檔案
- 當多個線程訪問同一塊資源時,很容易引發資料錯亂和資料安全問題
2.多線程的安全隱患樣本1)取錢
2)賣票
3.安全隱患分析
4.安全隱患解決方案——互斥鎖 1)互斥鎖原理圖解
2)互斥鎖的使用格式
@synchronized(鎖對象) { // 需要鎖定的代碼 }
3)互斥鎖的優缺點
- 優點:能有效防止因多線程搶奪資源造成的資料安全問題
- 缺點:需要消耗大量的CPU資源
4)互斥鎖的使用前提
5)相關專業術語:線程同步
- 線程同步的意思是:多條線程按順序地執行任務
- 互斥鎖,就是使用了線程同步技術
四.原子和非原子屬性1. OC在定義屬性時有nonatomic和atomic兩種選擇
- 原子屬性,為setter方法加鎖(預設就是atomic)
- 非原子屬性,不會為setter方法加鎖
3. atomic加鎖原理
@property (assign, atomic) int age;- (void)setAge:(int)age{ @synchronized(self) { _age = age; }}4. nnonatomic和atomic對比
- atomic:安全執行緒,需要消耗大量的資源
- nonatomic:非安全執行緒,適合記憶體小的行動裝置
5. iOS開發的建議
- 所有屬性都聲明為nonatomic
- 盡量避免多線程搶奪同一塊資源
- 盡量將加鎖、資源搶奪的商務邏輯交給伺服器端處理,減小移動用戶端的壓力
五. 線程間通訊1. 什麼叫做線程間通訊
- 在1個進程中,線程往往不是孤立存在的,多個線程之間需要經常進行通訊
2. 線程間通訊的體現
- 1個線程傳遞資料給另1個線程
- 在1個線程中執行完特定任務後,轉到另1個線程繼續執行任務
3. 線程間通訊常用方法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
4. 線程間通訊樣本——圖片下載