引言: 之前介紹過 線程的概念 和pthread的使用
線程執行的流程圖
線程執行的流程圖
圖解:
1.新建線程 調用start方法后線程進入就緒狀態 此時線程對象在可調度線程池
2.CPU會在線程之間調度
當線程執行完任務或異常時線程會自動銷毀
當調用調用sleep方法或等待同步鎖時
3.此時線程會進入阻塞狀態
如果調用sleep方法或等待同步鎖的時間到時 線程就會被CPU調度
線程的屬性
- name屬性 主要用于區分線程在線程異常時方便找出異常的線程
- threadPriority屬性 線程的優先級 取值范圍0~1.0 數值越大CPU在該線程調度的次數相對越多
NSThread創建線程的方法
- 方法一
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadTest) object:nil];
[thread start];
- 方法二
[NSThread detachNewThreadSelector:@selector(threadTest) toTarget:self withObject:nil];
- 方法三
[self performSelectorInBackground:@selector(threadTest) withObject:nil];
- 執行線程的方法(沒有參數形式)
- (void)threadTest {
NSLog(@"threadTest所在線程 -- %@", [NSThread currentThread]);
}
- 執行線程的方法(含參數)
- (void)threadTest:(NSString *)name {
NSLog(@"threadTest -- %@", name);
}
多線程操作共享資源
共享資源應使用線程的同步技術 讓多條線程按順序指向任務
可以使用互斥鎖 如果發現其他線程正在 執行鎖定代碼 線程會進入休眠 它可以有效防止多線程搶奪資源造成的數據安全問題
@synchronized(鎖對象) {需要鎖定的代碼}
加鎖會降低程序執行效率
自旋鎖 如果發現其他線程正在鎖定代碼 線程會用死循環的方式 一直等待鎖定代碼執行完成 它 不適合執行耗時代碼