异步执行+并发队列
2020-07-06 本文已影响0人
Jean_Lina
/**
* 异步执行 + 并发队列
* 特点:可以开启多个线程,任务交替(同时)执行。
*/
- (void)asyncConcurrent {
//打印当前线程
NSLog(@"currentThread---%@",[NSThread currentThread]);
NSLog(@"asyncConcurrent---begin");
dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
//追加任务1
for (int i = 0; i < 2; ++i) {
//模拟耗时操作
[NSThread sleepForTimeInterval:2];
//打印当前线程
NSLog(@"1---%@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
//追加任务2
for (int i = 0; i < 2; ++i) {
//模拟耗时操作
[NSThread sleepForTimeInterval:2];
//打印当前线程
NSLog(@"2---%@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
//追加任务3
for (int i = 0; i < 2; ++i) {
//模拟耗时操作
[NSThread sleepForTimeInterval:2];
//打印当前线程
NSLog(@"3---%@",[NSThread currentThread]);
}
});
NSLog(@"asyncConcurrent---end");
}
运行结果:
2020-07-06 20:42:18.289380+0800 GCD[15964:3050162] currentThread---<NSThread: 0x600001e82d00>{number = 1, name = main}
2020-07-06 20:42:18.289488+0800 GCD[15964:3050162] asyncConcurrent---begin
2020-07-06 20:42:18.289660+0800 GCD[15964:3050162] asyncConcurrent---end
2020-07-06 20:42:20.291936+0800 GCD[15964:3050315] 2---<NSThread: 0x600001ee9f40>{number = 7, name = (null)}
2020-07-06 20:42:20.291931+0800 GCD[15964:3050311] 1---<NSThread: 0x600001eda5c0>{number = 5, name = (null)}
2020-07-06 20:42:20.291967+0800 GCD[15964:3050310] 3---<NSThread: 0x600001e8bc40>{number = 6, name = (null)}
2020-07-06 20:42:22.292730+0800 GCD[15964:3050310] 3---<NSThread: 0x600001e8bc40>{number = 6, name = (null)}
2020-07-06 20:42:22.292730+0800 GCD[15964:3050315] 2---<NSThread: 0x600001ee9f40>{number = 7, name = (null)}
2020-07-06 20:42:22.292731+0800 GCD[15964:3050311] 1---<NSThread: 0x600001eda5c0>{number = 5, name = (null)}