多线程

GCD

创建串行队列,会开启1个线程,依次执行所有的任务

dispatch_queue_tmyQueue =dispatch_queue_create("myQ",NULL);

//打印当前线程

NSLog(@"%@",[NSThreadcurrentThread]);

//异步执行任务2参数1任务队列2任务

dispatch_async(myQueue, ^{

});

并行队列,会创建N个线程,同时执行多个任务

dispatch_queue_tmyQueue2 =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(myQueue2, ^{

[NSThreadsleepForTimeInterval:.5];

往界面中添加控件,在主线程中执行任务,回到主线程

dispatch_async(dispatch_get_main_queue(), ^{

});

});

NSOperation

- (void)viewDidLoad {

[superviewDidLoad];

NSOperationQueue*queue = [NSOperationQueuenew];

控制线程并行数量

queue.maxConcurrentOperationCount= 1;

NSInvocationOperation*op1 = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(run)object:nil];

NSBlockOperation*op2 = [NSBlockOperationblockOperationWithBlock:^{

for(inti=0; i<3; i++) {

[NSThreadsleepForTimeInterval:.5];

NSLog(@"任务二:%d",i);

}

}];

**控制任务之间的关系让op1任务依赖于op2**

[op1addDependency:op2];

**把任务添加到任务队列任务添加到队列的同时开始执行

[queueaddOperation:op1];

[queueaddOperation:op2];

}

NSThread

2.1开一个子线程

[NSThreaddetachNewThreadSelector:@selector(zixian)toTarget:selfwithObject:nil];

2.2在子线程中调用主线程

[selfperformSelectorOnMainThread:@selector(updataUIWithNumber:)withObject:@(i)waitUntilDone:NO];

3.多线程问题买票问题 

线程同步有三种方式:1.同步代码块 2.NSLock 3.NSCondition

-//同步代码块

@synchronized(self) {}

}

你可能感兴趣的:(多线程)