// 并发队列
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
// 异步执行
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"栅栏:并发异步1 %@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"栅栏:并发异步2 %@",[NSThread currentThread]);
}
});
dispatch_barrier_async(queue, ^{
NSLog(@"------------barrier------------%@", [NSThread currentThread]);
NSLog(@"******* 并发异步执行,但是34一定在12后面 *********");
});
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"栅栏:并发异步3 %@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 3; i++) {
NSLog(@"栅栏:并发异步4 %@",[NSThread currentThread]);
}
});
和group关联的API,会在所有任务执行完成后执行后续操作 "完成"会在全部执行完成后打印出来
NSArray *array = [NSArray arrayWithObjects:@"/Users/chentao/Desktop/copy_res/gelato.ds",
@"/Users/chentao/Desktop/copy_res/jason.ds",
@"/Users/chentao/Desktop/copy_res/jikejunyi.ds",
@"/Users/chentao/Desktop/copy_res/molly.ds",
@"/Users/chentao/Desktop/copy_res/zhangdachuan.ds",
nil];
NSString *copyDes = @"/Users/chentao/Desktop/copy_des";
NSFileManager *fileManager = [NSFileManager defaultManager];
dispatch_async(dispatch_get_global_queue(0, 0), ^(){
dispatch_apply([array count], dispatch_get_global_queue(0, 0), ^(size_t index){
NSLog(@"copy-%ld", index);
NSString *sourcePath = [array objectAtIndex:index];
NSString *desPath = [NSString stringWithFormat:@"%@/%@", copyDes, [sourcePath lastPathComponent]];
[fileManager copyItemAtPath:sourcePath toPath:desPath error:nil];
});
NSLog(@"完成");
});
基于GCD封装 配合NSOperationQueue实现多线程
暂停和取消不是立刻取消当前操作,而是等当前的操作执行完之后不再进行新的操作。