1.每個應(yīng)用程序至少有一個主線程彩掐,它的主要工作是:更新顯示UI界面铭若、處理用戶的觸摸事件等;如果需要執(zhí)行太耗時的操作狭握,就需要用到多線程闪金,多線程按抽象程度從低到高依次為:Thread,Cocoa Operations,GCD(ios4).
2.NSThread的初始化方法有三種:①動態(tài)方法:- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
例如:
// 初始化線程
NSThread?*thread?=?[[NSThread?alloc]?initWithTarget:self?selector:@selector(run)?object:nil];
//?設(shè)置線程的優(yōu)先級(0.0?-?1.0,1.0最高級)
thread.threadPriority?=1;
//?開啟線程
[thread?start];
②靜態(tài)方法:+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
例如:
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
//?調(diào)用完畢后论颅,會馬上創(chuàng)建并開啟新線程
③隱式創(chuàng)建:[self performSelectorInBackground:@selector(run) withObject:nil].
3.獲取當(dāng)前線程:NSThread *current = [NSThread currentThread];
獲取主線程:NSThread *main = [NSThread mainThread];
暫停當(dāng)前線程:① ?[NSThread sleepForTimeInterval:2]?
② ? NSDate *date = [NSDate dateWithTimeInterval:2.0f sinceDate:[NSDate date]];
? ? ? [NSThread sleepUntilDate:date]哎垦;
4.線程間的通信:
① ?在指定線程上執(zhí)行操作: [self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
② ?在主線程上執(zhí)行操作: ?[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
③? 在當(dāng)前線程執(zhí)行操作:[self performSelector:@selector(run) withObject:nil];
5.優(yōu)缺點(diǎn):
① ?優(yōu)點(diǎn):NSThread比其他兩種多線程方案較輕量級,更直觀地控制線程對象恃疯。
②? 缺點(diǎn):需要自己管理線程的生命周期漏设,線程同步。線程同步對數(shù)據(jù)的加鎖會有一定的系統(tǒng)開銷今妄。