多线程同步和异步

1.自创队列(GCD)
dispatch_queue_t queue= dispatch_queue_create("wendingding", NULL);
dispatch_sync(queue, ^{31 NSLog(@"下载图片1----%@",[NSThread currentThread]);32 });
2.同步
dispatch_async(dispatch_get_main_queue(), ^{

     }); 

3.异步
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_sync(queue ^{
});

NSOperation 1.同步
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue]; //主队列 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //自定义队列 NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ //任务执行 }]; [queue addOperation:operation];
2.异步
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^(){
NSLog(@"执行第1次操作,线程:%@", [NSThread currentThread]);
}];

NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^(){
NSLog(@"执行第2次操作,线程:%@", [NSThread currentThread]);
}];
// operation1依赖于operation2
[operation1 addDependency:operation2];

[queue addOperation:operation1];
[queue addOperation:operation2];

你可能感兴趣的:(多线程同步和异步)