一 創建和啓動
創建和啓動(推薦使用):
NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(download)object:nil];
thread.name =@"下載線程";
[thread start];
參數分析:調用方法、傳遞參數
PS:init方法後僅僅是創建了線程對象,需要通過start方法將線程對象放入可調用線程池。一個NSThread對象代表一條線程。
其他兩種常用線程的方法:
創建線程並自動啓動:
[NSThreaddetachNewThreadSelector:@selector(download)toTarget:selfwithObject:nil];
隱式創建線程並啓動:
[selfperformSelectorInBackground:@selector(download)withObject:nil];
分析:兩種方法創建線程更爲快捷,但是兩者方法返回都爲void即沒有返回線程對象,無法對線程進行一些操作。
二 線程狀態
New:新建:通過init方法創建的線程對象還未進入可調度線程池。
Runnable:就緒:使用start方法、線程進入可調度線程池中。或CPU調度完當前線程後,轉而調度其他線程。(CPU一次只能運行一個線程。只用調度夠快可以產生多線程同時運行的效果)或slepp到時,得到互斥鎖。
Running:運行時:CPU調度到當前線程,線程運行。
Blocked:堵塞:在running狀態調用了sleep方法,線程進入睡眠等待互斥鎖。
Dead:死亡:線程執行完畢,或者異常、強制退出。PS:線程對象Dead後不能再次執行,想要再次執行需要重新創建線程。
三 線程間通信
從其他線程回到主線程:
[self performSelectorOnMainThread:@selector(mySetView:) withObject:date waitUntilDone:YES];
分析:
第三個參數:是否等待主線程執行完再執行自線程中接下來的內容。
從某個線程跳到其他線程:
- (void)performSelector:(SEL)aSelectoronThread:(NSThread thrwithObject:(id)arg waitUntilDone:(BOOL)wait;