//NSOpertionQueue NSOperation //Queue //主隊列 和 自定義隊列 //主隊列是運行在主線程當中,自定義隊列運行在后臺 //NSOperation 定義需要執(zhí)行的操作(任務) //定義需要的操作,然后把該操作添加到合適的隊列中 //三個步驟 //1.創(chuàng)建隊列對象 //2.創(chuàng)建操作對象 //3.把操作對象添加到隊列之中,等待隊列分配線程執(zhí)行操作 //1.創(chuàng)建隊列 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //設置最大并發(fā)操作數(shù) //隊列中最多有幾個操作同時執(zhí)行 queue.maxConcurrentOperationCount = 1; //是否暫停執(zhí)行隊列中的線程 [queue setSuspended:YES]; //2.創(chuàng)建操作 //NSOperation 不能直接使用 //使用子類的對象 兩種方式1、直接創(chuàng)建 2、使用block創(chuàng)建 NSOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread1:) object:@"op1 "]; NSOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread2:) object:@"op2 "]; /* NSBlockOperation *op3 = [[NSBlockOperation alloc] init]; [op3 addExecutionBlock:^{ //具體要執(zhí)行的操作 }]; */ //3.把操作加入到隊列中 [queue addOperation:op1]; [queue addOperation:op2]; //加入之后,如果有操作,那隊列就會自動執(zhí)行 //4.設置操作的優(yōu)先級 [op1 setQueuePRiority:NSOperationQueuePriorityLow]; [op2 setQueuePriority:NSOperationQueuePriorityVeryHigh]; //5.設置操作之間的依賴關系 [op2 addDependency:op1]; //op2的執(zhí)行依賴于op1,保證op1肯定op2之前執(zhí)行 //是否重新讓隊列執(zhí)行 [queue setSuspended:NO]; //回到主線程打印輸出 for (int i = 0; i < 50; i ++) { NSLog(@"主線程 : %d", i); }}- (void)thread1:(NSString *)name{ //具體要執(zhí)行的操作 for (int i = 0; i < 50; i ++) { NSLog(@"多線程 %@: %d", name, i); }}- (void)thread2:(NSString *)name{ for (int i = 0; i < 50; i ++) { NSLog(@"多線程 %@: %d", name, i); }}
新聞熱點
疑難解答