iOS知识复习总结(七)线程

2017-03-16  本文已影响0人  空幻XY

1.NSOperation

//并行队列(只有并行队列)

NSOperationQueue *queue = [NSOperationQueue new];

//任务

NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"op1 begin %@", [NSThread currentThread]);

sleep(2);

NSLog(@"op1 end %@", [NSThread currentThread]);

}];

NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"op2 begin %@", [NSThread currentThread]);

sleep(4);

NSLog(@"op2 end %@", [NSThread currentThread]);

}];

NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"op3 begin %@", [NSThread currentThread]);

sleep(2);

NSLog(@"op3 end %@", [NSThread currentThread]);

}];

NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"op4 begin %@", [NSThread currentThread]);

sleep(2);

NSLog(@"op4 end %@", [NSThread currentThread]);

}];

NSBlockOperation *op5 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"op5 begin %@", [NSThread currentThread]);

sleep(2);

NSLog(@"op5 end %@", [NSThread currentThread]);

}];

NSBlockOperation *op6 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"op6 begin %@", [NSThread currentThread]);

sleep(2);

NSLog(@"op6 end %@", [NSThread currentThread]);

}];

NSBlockOperation *op7 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"op7 begin %@", [NSThread currentThread]);

sleep(2);

NSLog(@"op7 end %@", [NSThread currentThread]);

}];

NSBlockOperation *op8 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"op8 begin %@", [NSThread currentThread]);

sleep(2);

NSLog(@"op8 end %@", [NSThread currentThread]);

}];

NSBlockOperation *op9 = [NSBlockOperation blockOperationWithBlock:^{

NSLog(@"op9 begin %@", [NSThread currentThread]);

sleep(2);

NSLog(@"op9 end %@", [NSThread currentThread]);

}];

/*

[queue addOperation:op1];

[queue addOperation:op2];*/

//waitUntilFinished:下方的代码是否要等待队列中的任务完成后再执行

//线程的最大并发数量,最佳值3~5

queue.maxConcurrentOperationCount = 3;

//添加依赖 让op1任务 需要在op8 op5都完成之后才能执行

[op1 addDependency:op8];

[op1 addDependency:op5];

[queue addOperations:@[op1, op2, op3, op4, op5, op6, op7, op8, op9] waitUntilFinished:NO];

NSLog(@"waitUntilFinished");

//取消队列中的所有任务

[queue cancelAllOperations];

//取消队列中的一些任务

[op3 cancel]; //已经开始执行的任务,不能单独取消

[op6 cancel];

//暂停队列  suspended:暂停

queue.suspended = YES;

sleep(10);

queue.suspended = NO;

dispatch_async(dispatch_get_global_queue(0, 0), ^{

dispatch_async(dispatch_get_main_queue(), ^{

});

});

[[NSOperationQueue new] addOperationWithBlock:^{

NSLog(@"%@", [NSThread currentThread]);

[[NSOperationQueue mainQueue] addOperationWithBlock:^{

}];

}];

2.GCD


上一篇 下一篇

猜你喜欢

热点阅读