- pthread:
//创建线程 pthread_t pthread; pthread_create(&pthread, NULL, run, NULL);
void *run(){ NSLog(@"在子线程中执行!!!!"); for (int i =1; i < 10; i++) { NSLog(@"%d",i); sleep(1); if (i == 5) { //取消线程操作: pthread_cancel(pthread); } } return NULL; }
- NSThread
一共有四种创建方式:
1.alloc方式创建:NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil]; thread.name =@"threadName";//可以设置线程的name,用以区分线程 thread.threadPriority = 0.6;//设置线程的优先级,优先级越高执行的概率越高 [self.thread start];//用以启动线程,否则不执行,对应的有一个静态方法:[NSThread exit]退出线程
2.detachNewThreadSelector方式创建:
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
3.performSelectorInBackground方式创建:
//有两种方式
//创建子线程:
[self performSelectorInBackground:@selector(run) withObject:nil];
//回到主线程:
[self performSelectorOnMainThread:@selector(backMainThread) withObject:nil waitUntilDone:YES];
- 线程锁
作用:保证代码能够完整执行,其他线程只能在锁外等待,直到解锁才能执行- NSLock
NSLock *lock = [[NSLock alloc]init]; [lock lock]; //需要保护的代码 ... [lock unlock];
- @synchronized
@synchronized (self) { //需要保护的代码 ... }
网友评论