见视频 0423
ios中有两种多线程方式,一种是C++自带的GCD,另一种是OC中的NSOperation
1、GCD案列
//1、创建一个队列,DISPATCH_QUEUE_SERIAL表示串行
dispatch_queue_t q = dispatch_queue_create("id", DISPATCH_QUEUE_SERIAL);
//2把任务加入队列,dispatch_sync表示同步,同步不用创建新的线程
for (int i = 0; i< 10; i++) {
dispatch_sync(q, ^{
NSLog(@"任务=%d,%@",i,[NSThread currentThread]);
});
}
//创建并行队列,DISPATCH_QUEUE_CONCURRENT表示并行
dispatch_queue_t q = dispatch_queue_create("id", DISPATCH_QUEUE_CONCURRENT);
//2把任务加入队列,dispatch_async表示异步,异步会创建新线程
for (int i = 0; i< 10; i++) {
dispatch_async(q, ^{
NSLog(@"任务=%d,%@",i,[NSThread currentThread]);
});
}
2、NSOperation案列
//异步队列
NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
//添加到队列
[myQueue addOperation:block];
//同步队列,所有任务在主线程执行
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];