- (void)testWithType:(NSInteger)type{
for (int i=0; i<10; i++) {
NSLog(@"operation%zd = %d - %@",type,i,[NSThread currentThread]);
}
}
- ** NSInvocationOperation**
//默认是主线程 搭配NSOperationQueue实现多线程
NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(testWithType:) object:@(1)];
[invocationOperation start];
- ** NSBlockOperation**
//默认是主线程 搭配NSOperationQueue实现多线程
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
for (int i=0; i<3; i++) {
NSLog(@"主线程 = %d - %@",i,[NSThread currentThread]);
}
}];
//添加任务会自动加入到多线程
[blockOperation addExecutionBlock:^{
for (int i=0; i<3; i++) {
NSLog(@"可以实现多线程 = %d - %@",i,[NSThread currentThread]);
}
}];
[blockOperation start];
- 线程依赖
//线程依赖
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
[self testWithType:1];//多线程
}];
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
[self testWithType:2];//多线程
}];
NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
[self testWithType:3];//多线程
}];
NSBlockOperation *operationAfter = [NSBlockOperation blockOperationWithBlock:^{
for (int i=0; i<10; i++) {
NSLog(@"operationAfter = %d - %@",i,[NSThread currentThread]);
}
}];
[operationAfter addDependency:operation1];
[operationAfter addDependency:operation2];
[operationAfter addDependency:operation3];
//operationAfter 依赖于 operation1,operation2,operation3
[queue addOperation:operation1];
[queue addOperation:operation2];
[queue addOperation:operation3];
[queue addOperation:operationAfter];
- 线程并发控制
// 创建队列,默认并发
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 最大并发数: =1为串行; >1为并行;
queue.maxConcurrentOperationCount = 1;
// 添加操作到队列
[queue addOperationWithBlock:^{
for (int i=0; i<10; i++) {
NSLog(@"addOperationWithBlock1 = %d - %@",i,[NSThread currentThread]);
}
}];
[queue addOperationWithBlock:^{
for (int i=0; i<10; i++) {
NSLog(@"addOperationWithBlock2 = %d - %@",i,[NSThread currentThread]);
}
}];
```[图片上传失败...(image-355539-1635760294185)]
网友评论