多線程之NSOpertionQueue操作隊列,nsoperationqueue
//NSOpertionQueue NSOperation //Queue //主隊列 和 自訂隊列 //主隊列是運行在主線程當中,自訂隊列運行在後台 //NSOperation 定義需要執行的操作(任務) //定義需要的操作,然後把該操作添加到合適的隊列中 //三個步驟 //1.建立隊列對象 //2.建立操作對象 //3.把操作對象添加到隊列之中,等待隊列分配線程執行操作 //1.建立隊列 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //設定最大並行作業數 //隊列中最多有幾個操作同時執行 queue.maxConcurrentOperationCount = 1; //是否暫停執行隊列中的線程 [queue setSuspended:YES]; //2.建立操作 //NSOperation 不能直接使用 //使用子類的對象 兩種方式1、直接建立 2、使用block建立 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:^{ //具體要執行的操作 }]; */ //3.把操作加入到隊列中 [queue addOperation:op1]; [queue addOperation:op2]; //加入之後,如果有操作,那隊列就會自動執行 //4.設定作業的優先順序 [op1 setQueuePriority:NSOperationQueuePriorityLow]; [op2 setQueuePriority:NSOperationQueuePriorityVeryHigh]; //5.設定作業之間的依賴關係 [op2 addDependency:op1]; //op2的執行依賴於op1,保證op1肯定op2之前執行 //是否重新讓隊列執行 [queue setSuspended:NO]; //回到主線程列印輸出 for (int i = 0; i < 50; i ++) { NSLog(@"主線程 : %d", i); }}- (void)thread1:(NSString *)name{ //具體要執行的操作 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); }}