1.建立和啟動線程 一個NSThread對象就代表一條線程; 建立,啟動線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];[thread start];
2.線程相關用法 主線程相關用法
1 + (NSThread *)mainThread;2 - (BOOL)isMainThread;3 + (BOOL)isMainThread;
獲得當前線程
1 NSThread *current = [NSThread currentThread];
線程的調度優先順序
1 + (double)threadPriority;2 + (BOOL)setThreadPriority:(double)p;3 - (double)threadPriority;4 - (BOOL)setThreadPriority:(double)p;
調度的優先順序取值範圍是0.0 ~ 1.0, 預設0.5, 值越大, 優先順序越高; 線程的名字
1 - (void) setName:(NSString *)n;2 - (NSString *)name;
建立線程後自動啟動線程
1 [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
隱式建立線程並啟動線程
1 [self performSelectorInBackground:@selector(run) withObject:nil];
3.線程的五種狀態 建立(New) 就緒(Runnable) 運行(Running) 阻塞(Blocked) 死亡(Dead) 4.控制線程狀態 啟動線程
1 - (void)start;
阻塞線程
1 + (void)sleepUntilDate:(NSDate *)date;2 + (void)sleepForTimeInterval:(NSTimeInterval)ti;
強制停止線程
1 + (void)exit;
5.多線程的安全隱患 資源共用:多個線程訪問同一塊資源; 處理共用資料時很容易引發資料錯亂和資料安全問題; 6.安全隱患解決--互斥鎖 互斥鎖使用格式:@synchroniazed(鎖對象) { 代碼 } 互斥鎖的優缺點: 優點:能有效防止因多線程搶奪資源造成的資料安全問題; 缺點:大量消耗CPU資源; 互斥鎖的使用前提:多條線程搶奪同一塊資源; 相關術語:線程同步; 線程同步的含義:多條線程按順序執行任務; 互斥鎖就是使用了線程同步技術; 7.原子屬性和非原子屬性 OC在定義屬性時有nonatomic和atomic兩種選擇: atomic:原子屬性,為setter方法加鎖(預設就是atomic); nonatomic:非原子屬性,不會為setter方法加鎖; atomic加鎖原理:
1 @property (assign, atomic) int age;2 - (void)setAge:(int)age3 {4 @synchronized(self) {5 _age = age;6 }7 } nonatomic和atomic對比 nonatomic:安全執行緒,需要消耗大量的資源; atomic:線程不安全,適合記憶體較小的行動裝置; iOS的開發建議: 所有屬性都定義為nonatomic; 盡量避免多線程搶奪同一塊資源; 盡量將加鎖,資源搶奪的商務邏輯都交給伺服器端處理,減少移動用戶端的壓力; 8.線程間通訊 一個線程傳遞資料給另一個線程; 一個線程執行完任務,轉到另一個線程繼續執行任務; 線程之間常用的通訊方法
1 - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;2 - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;