/**
* 异步执行 + 串行队列
* 特点:会开启新线程,但是因为任务是串行的,执行完一个任务,再执行下一个任务。
*/
- (void)asyncSerial {
//打印当前线程
NSLog(@"currentThread---%@",[NSThread currentThread]);
NSLog(@"asyncSerial---begin");
dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_SERIAL);
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(@"asyncSerial---end");
}
运行结果:
2020-07-06 20:55:53.020073+0800 GCD[16251:3139547] currentThread---<NSThread: 0x6000005b0180>{number = 1, name = main}
2020-07-06 20:55:53.020181+0800 GCD[16251:3139547] asyncSerial---begin
2020-07-06 20:55:53.020276+0800 GCD[16251:3139547] asyncSerial---end
2020-07-06 20:55:55.022406+0800 GCD[16251:3139638] 1---<NSThread: 0x6000005da900>{number = 7, name = (null)}
2020-07-06 20:55:57.024138+0800 GCD[16251:3139638] 1---<NSThread: 0x6000005da900>{number = 7, name = (null)}
2020-07-06 20:55:59.029368+0800 GCD[16251:3139638] 2---<NSThread: 0x6000005da900>{number = 7, name = (null)}
2020-07-06 20:56:01.032945+0800 GCD[16251:3139638] 2---<NSThread: 0x6000005da900>{number = 7, name = (null)}
2020-07-06 20:56:03.033199+0800 GCD[16251:3139638] 3---<NSThread: 0x6000005da900>{number = 7, name = (null)}
2020-07-06 20:56:05.033421+0800 GCD[16251:3139638] 3---<NSThread: 0x6000005da900>{number = 7, name = (null)}
网友评论