优点:NSThread 比其他两个轻量级
缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销
NSThread 有两种直接创建方式:
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument
1、[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];
2、NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:nil];
[myThread start];
用NSObject的类方法 performSelectorInBackground:withObject: 创建一个线程:
[self performSelectorInBackground:@selector(doSomething) withObject:nil];
如果要停止子线程,有两种方法:
第一种,是在子线程中执行:
[NSThread exit];
另一种是在主线程执行:
[myThread cancel];
要注意的是,[mThread cancel]; 并不能exit线程,只是标记为canceled,但线程并没有死掉。加入你在子线程中执行了一个循环,则cancel后,循环还在继续,你需要在循环的条件判断中加入 !mThread.isCancelled 来判断子线程是否已经被cancel来决定是否继续循环。
下面是demo:
@synthesize mThread;
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"main thread:%@",[NSThread currentThread]);
mThread=[[NSThread alloc] initWithTarget:self selector:@selector(subThreadMethod) object:nil];
[NSThread detachNewThreadSelector:@selector(performMethod) toTarget:self withObject:nil];
}
-(void)subThreadMethod{
int i=1;
while (i++>0 && ![[NSThread currentThread]isCancelled]) {
NSLog(@"subthread i:%d ,thread:%@",i,[NSThread currentThread]);
}
}
- (IBAction)startThread:(id)sender {
NSLog(@"startThread....");
[mThread start];
}
- (IBAction)stopThread:(id)sender {
NSLog(@"mThread.isCancelled: %d",mThread.isCancelled);
if (!mThread.isCancelled) {
[mThread cancel];
// [mThread exit]; //exit 是类方法,不可以用在对象上
}
}
- (IBAction)performOnSubThread:(id)sender {
//在子线程调用方法
[self performSelector:@selector(performMethod) onThread:mThread withObject:nil waitUntilDone:NO];
}
-(void)performMethod{
NSLog(@"performMethod.... thread:%@",[NSThread currentThread]);
}
@end