- pthread:
//創(chuàng)建線程 pthread_t pthread; pthread_create(&pthread, NULL, run, NULL);
void *run(){ NSLog(@"在子線程中執(zhí)行!!!!"); for (int i =1; i < 10; i++) { NSLog(@"%d",i); sleep(1); if (i == 5) { //取消線程操作: pthread_cancel(pthread); } } return NULL; }
- NSThread
一共有四種創(chuàng)建方式:
1.alloc方式創(chuàng)建:NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil]; thread.name =@"threadName";//可以設(shè)置線程的name葬燎,用以區(qū)分線程 thread.threadPriority = 0.6;//設(shè)置線程的優(yōu)先級(jí)绰精,優(yōu)先級(jí)越高執(zhí)行的概率越高 [self.thread start];//用以啟動(dòng)線程秘遏,否則不執(zhí)行愿卒,對(duì)應(yīng)的有一個(gè)靜態(tài)方法:[NSThread exit]退出線程
2.detachNewThreadSelector方式創(chuàng)建:
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
3.performSelectorInBackground方式創(chuàng)建:
//有兩種方式
//創(chuàng)建子線程:
[self performSelectorInBackground:@selector(run) withObject:nil];
//回到主線程:
[self performSelectorOnMainThread:@selector(backMainThread) withObject:nil waitUntilDone:YES];
- 線程鎖
作用:保證代碼能夠完整執(zhí)行,其他線程只能在鎖外等待,直到解鎖才能執(zhí)行- NSLock
NSLock *lock = [[NSLock alloc]init]; [lock lock]; //需要保護(hù)的代碼 ... [lock unlock];
- @synchronized
@synchronized (self) { //需要保護(hù)的代碼 ... }