一個正在執行的應用程式就是一個「行程(Process)」,而每個行程預設都會開啟一條「主執行緒(Main Thread)」。在主執行緒中,任務是序列執行的——也就是有多件事要辦時,只能一件接一件地依序完成。為了提升效率,我們會在行程中開啟多條執行緒,讓不同任務能夠並行處理。
在 iOS 程式中,處理使用者觸控事件、刷新介面等操作必須放在主執行緒上。因此,那些較耗費資源的任務(例如從網路抓取資料、下載檔案)就應該放到子執行緒中進行。否則一旦主執行緒被阻塞,畫面就會出現卡頓,直接影響使用者體驗。
(1)NSThread:最原始的執行緒操作方式,屬於輕量級方案,能更直觀地控制執行緒物件。缺點是需要自行管理執行緒生命週期,若要實現同步還得自行加鎖,會增加系統開銷。
(2)NSOperation 與 NSOperationQueue:以物件導向的方式封裝要執行的操作,再把操作放進 NSOperationQueue 中異步執行,無需自行管理執行緒與同步問題。
(3)Grand Central Dispatch(GCD):C 語言的 API,提供了多項新特性來實現多核設備的並行編程。
本文先聚焦在 NSThread 的使用。
NSThread 是執行緒類別,一個 NSThread 實例即代表一條執行緒。
取得主執行緒:
NSThread *mainThread = [NSThread mainThread];
取得當前執行緒:
NSThread *currentThread = [NSThread currentThread];
(1)動態方法:透過物件方法建立執行緒,需要手動啟動:
//初始化線程 NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(startThread:) object: @"ios"]; thread1.name = @"thread1"; //開啟線程 [thread1 start];
啟動後被呼叫的方法:
-(void)startThread:(NSString *)parm{ NSThread *currentThread = [NSThread currentThread]; for (int i=0; i<10; i++) { NSLog(@"參數為 %@, 當前的線程為 %@, 線程的名字為 %@",parm,currentThread,currentThread.name); } }
(2)靜態方法:透過類方法開啟執行緒,由系統自動呼叫:
[NSThread detachNewThreadSelector:@selector(startThread:) toTarget:self withObject:@"jredu"];
(3)隱式方法開啟執行緒:
[self performSelectorInBackground:@selector(startThread:) withObject:@"apple"];
//方法一 [NSThread sleepForTimeInterval:2]; //方法二 NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]]; [NSThread sleepUntilDate:date];
(1)在指定執行緒執行:
[self performSelector:@selector(run) onThread:thread1 withObject:nil waitUntilDone:YES];
(2)在主執行緒執行:
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
(3)在當前執行緒執行:
[self performSelector:@selector(run) withObject:nil];
透過 NSThread,你能夠清楚掌握每條執行緒的建立與調度。當需求變得更複雜、需要更好的同步與管理時,再進一步改用 NSOperation 或 GCD 會是更合適的選擇。