NSThread
NSThread *myThread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"jack"];
[myThread start]; // 開始
- 創建線程后自動啟動線程
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
- 隱身創建并啟動線程
[self performSelectorInBackground:@selector(run:) withObject:nil];
- 讓線程睡眠2秒(阻塞2秒)
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
- 啟動線程
- 進入就緒狀態 -> 運行狀態。當線程任務執行完畢,自動進入死亡狀態
- (void)start;
● 強制停止線程
- (void)exit;
注意:一旦線程停止(死亡)了,就不能再次開啟任務
● 互斥鎖使用格式
@synchronized(鎖對象)
{ // 需要鎖定的代碼 }
注意:鎖定1份代碼只用1把鎖,用多把鎖是無效的
● 互斥鎖的優缺點
● 優點:能有效防止因多線程搶奪資源造成的數據安全問題
● 缺點:需要消耗大量的CPU資源
● 互斥鎖的使用前提:多條線程搶奪同一塊資源