NSThread创建方式

三种创建方式:

1.通过alloc init 方式创建线程并执行

NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(runThread) object:nil];

[thread1 setName:@"Namethread1"];//获取线程name [NSThread currentThread].name;可用于判断线程问题

[thread1 setThreadPriority:0.5];//线程优先级,越大优先级越高

[thread1 start];

- (void)runThread{//子线程

for (int i = 0,i<10,i++){

NSLog(@"%d",i);

sleep(1);

if(i=10){//如果i为10的话,回到主线程

[self performSelectorOnMainThread:@selector(runMainThread) withObject:nil waitUntilDone:YES];

}

}

}

- (void)runMainThread{

NSLog(@"回到主线程");

}

2.通过 detachNewThreadSelector 创建线程并执行

[NSThread detachNewThreadSelector:@selector(runThread) toTarget:self withObject:nil];

3.通过 performSelectorInBackground 创建线程并执行

[self performSelectorInBackground:@selector(runThread) withObject:nil];

加锁:

1.@synchronized(self){

}

2.NSCondiction *condition = [[NSCondiction alloc]init];

[condition lock];

[condition unlock];

3.nslock

 

posted @ 2017-03-18 13:56  柳仙慧子  阅读(182)  评论(0编辑  收藏  举报