同步执行 + 串行队列

2020-07-06  本文已影响0人  Jean_Lina
/**
 * 同步执行 + 串行队列
 * 特点:不会开启新线程,在当前线程执行任务。任务是串行的,执行完一个任务,再执行下一个任务。
 */
- (void)syncSerial {
    //打印当前线程
    NSLog(@"currentThread---%@",[NSThread currentThread]);
    NSLog(@"syncSerial---begin");
    dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_sync(queue, ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            //模拟耗时操作
            [NSThread sleepForTimeInterval:2];
            //打印当前线程
            NSLog(@"1---%@",[NSThread currentThread]);
        }
    });
    dispatch_sync(queue, ^{
        // 追加任务2
        for (int i = 0; i < 2; ++i) {
            //模拟耗时操作
            [NSThread sleepForTimeInterval:2];
            //打印当前线程
            NSLog(@"2---%@",[NSThread currentThread]);
        }
    });
    dispatch_sync(queue, ^{
        // 追加任务3
        for (int i = 0; i < 2; ++i) {
            //模拟耗时操作
            [NSThread sleepForTimeInterval:2];
            //打印当前线程
            NSLog(@"3---%@",[NSThread currentThread]);
        }
    });
    NSLog(@"syncSerial---end");
}
运行结果:
2020-07-06 20:49:09.521419+0800 GCD[16131:3095672] currentThread---<NSThread: 0x60000185a140>{number = 1, name = main}
2020-07-06 20:49:09.521539+0800 GCD[16131:3095672] syncSerial---begin
2020-07-06 20:49:11.522312+0800 GCD[16131:3095672] 1---<NSThread: 0x60000185a140>{number = 1, name = main}
2020-07-06 20:49:13.523524+0800 GCD[16131:3095672] 1---<NSThread: 0x60000185a140>{number = 1, name = main}
2020-07-06 20:49:15.524799+0800 GCD[16131:3095672] 2---<NSThread: 0x60000185a140>{number = 1, name = main}
2020-07-06 20:49:17.525834+0800 GCD[16131:3095672] 2---<NSThread: 0x60000185a140>{number = 1, name = main}
2020-07-06 20:49:19.526351+0800 GCD[16131:3095672] 3---<NSThread: 0x60000185a140>{number = 1, name = main}
2020-07-06 20:49:21.527517+0800 GCD[16131:3095672] 3---<NSThread: 0x60000185a140>{number = 1, name = main}
2020-07-06 20:49:21.527653+0800 GCD[16131:3095672] syncSerial---end
上一篇 下一篇

猜你喜欢

热点阅读