多线程 队列的简单操作
NSOperationQueue *queue = [[NSOperationQueuealloc]init];
queue.maxConcurrentOperationCount = 2;
//线程池中的线程数,也就是并发操作数。默认情况下是-1,-1表示没有限制,这样会同时运行队列中的全部的操作。
for (NSInteger i = 0 ; i <1000000;i ++ ) {
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
sleep(1);
NSLog(@"%ld%@",i,[NSThread currentThread]);
}];
[queue addOperation:operation];
}
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
sleep(1);
NSLog(@"外加0%@",[NSThreadcurrentThread]);
}];
NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
sleep(1);
NSLog(@"外加1%@",[NSThreadcurrentThread]);
}];
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
sleep(1);
NSLog(@"外加2%@",[NSThreadcurrentThread]);
}];
[operation addDependency:operation2];//添加依赖关系改变执行顺序
[operation2 setQueuePriority:NSOperationQueuePriorityHigh];//设置operation2为高优先级先执行
[queue addOperation:operation];
[queue addOperation:operation1];
[queue addOperation:operation2];
[queue addOperationWithBlock:^{
NSLog(@"执行一个新的操作,线程:%@", [NSThreadcurrentThread]);
}];
// 阻塞当前线程,等待queue的所有操作执行完毕
[queue waitUntilAllOperationsAreFinished];
[queue setSuspended:YES];//暂停
[queue setSuspended:NO];//恢复
[queue cancelAllOperations];//取消所有操作