您的位置:首页 > 理论基础 > 计算机网络

第02天多线程网络:(10):NSOperationQueue的基本使用

2017-04-18 00:00 274 查看
#####一、10.NSOperationQueue的基本使用
code
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{//NSInvocationOperation[self invocationOperation];// [self blockOperation];}#pragma mark 2、Block- (void)blockOperation{// 1.封装操作NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{NSLog(@"1 ---- %@",[NSThread currentThread]);}];NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{NSLog(@"2 ---- %@",[NSThread currentThread]);}];NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{NSLog(@"3 ---- %@",[NSThread currentThread]);}];// 1.1. 追加任务[op1 addExecutionBlock:^{NSLog(@"4 ---- %@",[NSThread currentThread]);}];[op2 addExecutionBlock:^{NSLog(@"5 ---- %@",[NSThread currentThread]);}];[op3 addExecutionBlock:^{NSLog(@"6 ---- %@",[NSThread currentThread]);}];// 2.创建队列NSOperationQueue *queue = [[NSOperationQueue alloc]init];// 3.添加到队列里面去[queue addOperation:op1];[queue addOperation:op2];[queue addOperation:op3];// 简便方法// 1.创建操作, 2.添加操作到队列中[queue addOperationWithBlock:^{NSLog(@"7 ---- %@",[NSThread currentThread]);}];/*Log3 ---- <NSThread: 0x618000260700>{number = 6, name = (null)}6 ---- <NSThread: 0x610000079680>{number = 8, name = (null)}1 ---- <NSThread: 0x60800007c340>{number = 4, name = (null)}7 ---- <NSThread: 0x60000007a900>{number = 3, name = (null)}2 ---- <NSThread: 0x60000007aa00>{number = 7, name = (null)}4 ---- <NSThread: 0x60800007c580>{number = 5, name = (null)}5 ---- <NSThread: 0x60800007c440>{number = 9, name = (null)}*/}#pragma mark 1、NSInvocationOperation- (void)invocationOperation{// 1.创建操作,封装任务NSInvocationOperation *op1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download1) object:nil];NSInvocationOperation *op2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download1) object:nil];NSInvocationOperation *op3 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download1) object:nil];// 2.创建队列/*GCD :(顺序执行)串行队列: create 主队列(随机执行)并发队列: create 全局并发队列NSOperation :主队列 [NSOperationQueue mainQueue] 跟GCD的主队列一样非主队列 [[NSOperationQueue alloc]init] 非常特殊(同时具备并发和串行的功能) // 默认情况下是并发队列*/NSOperationQueue *queue = [[NSOperationQueue alloc]init];[queue addOperation:op1]; // 内部已经调用了 [op1 start];[queue addOperation:op2];[queue addOperation:op3];/*Log--- -[ViewController download1] ---<NSThread: 0x60000007f0c0>{number = 4, name = (null)}--- -[ViewController download1] ---<NSThread: 0x610000078b80>{number = 3, name = (null)}--- -[ViewController download1] ---<NSThread: 0x61800007c140>{number = 5, name = (null)}*/}- (void)download1{NSLog(@"--- %s ---%@",__func__ ,[NSThread currentThread]);}@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Objective-C 多线程