代码如下:
#pragma mark TODO:可取消的group
- (void)test3 {
dispatch_group_t group = dispatch_group_create ();
dispatch_queue_t pp = dispatch_queue_create ("ssss", DISPATCH_QUEUE_SERIAL);
NSMutableArray *kk = @[].mutableCopy;
__block dispatch_block_t block111;
dispatch_apply (10, pp, ^(size_t index) {
dispatch_block_t block = dispatch_block_create (0, ^{
NSLog (@"index:%d %@", index, [NSThread currentThread]);
[kk removeObject:block];
if (index > 5) {
for (dispatch_block_t tmp in kk) {
dispatch_block_cancel (tmp);
}
}
});
dispatch_async (pp, block);
[kk addObject:block];
dispatch_group_wait (group, DISPATCH_TIME_FOREVER);
});
dispatch_group_notify (group, pp, ^{
NSLog (@"任务已经完成");
});
}
#pragma mark TODO: 可取消的NSOperationQueue
- (void)test2 {
NSOperationQueue *oq = [[NSOperationQueue alloc] init];
NSMutableArray *opArryM = @[].mutableCopy;
NSBlockOperation *cureent;
BOOL stop = NO;
for (int i = 0; i < 10; i++) {
__block int x = i;
NSBlockOperation *bo1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog (@"请求%d", x);
if (x > 5) {
[oq cancelAllOperations];
}
}];
if (cureent) {
[bo1 addDependency:cureent];
cureent = bo1;
} else {
cureent = bo1;
}
[opArryM addObject:bo1];
}
[oq addOperations:opArryM waitUntilFinished:YES];
[oq addBarrierBlock:^{
NSLog (@"执行完成");
}];
self.task = oq;
}
- (void)test {
dispatch_group_t group = dispatch_group_create ();
dispatch_queue_t pp = dispatch_queue_create ("ssss", DISPATCH_QUEUE_SERIAL);
dispatch_group_enter (group);
dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), pp, ^{
NSLog (@"任务1");
NSLog (@"任务1===%@", [NSThread currentThread]);
dispatch_group_leave (group);
});
dispatch_group_wait (group, DISPATCH_TIME_FOREVER);
dispatch_group_enter (group);
dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), pp, ^{
NSLog (@"任务2");
NSLog (@"任务2===%@", [NSThread currentThread]);
dispatch_group_leave (group);
});
dispatch_group_wait (group, DISPATCH_TIME_FOREVER);
dispatch_group_enter (group);
dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), pp, ^{
NSLog (@"任务3");
NSLog (@"任务3===%@", [NSThread currentThread]);
dispatch_group_leave (group);
});
dispatch_group_notify (group, dispatch_get_global_queue (0, 0), ^{
NSLog (@"任务完成");
});
}
- (void)test1 {
NSOperationQueue *oq = [[NSOperationQueue alloc] init];
NSBlockOperation *bo1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog (@"请求1");
NSLog (@"请求1===%@", [NSThread currentThread]);
}];
NSBlockOperation *bo2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog (@"请求2");
NSLog (@"请求2===%@", [NSThread currentThread]);
[oq cancelAllOperations];
}];
NSBlockOperation *bo3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog (@"请求3");
NSLog (@"请求3===%@", [NSThread currentThread]);
}];
[bo3 addDependency:bo2];
[bo2 addDependency:bo1];
[oq addOperations:@[bo3, bo2, bo1] waitUntilFinished:YES];
}
网友评论