美文网首页
同步执行 + 主队列

同步执行 + 主队列

作者: Jean_Lina | 来源:发表于2020-07-06 21:12 被阅读0次
    使用 NSThread 的 detachNewThreadSelector 方法会创建线程,并自动启动线程执行 selector 任务
    [NSThread detachNewThreadSelector:@selector(syncMain) toTarget:self withObject:nil];
    
    /**
     * 同步执行 + 主队列
     * 特点(主线程调用):互等卡主不执行。
     * 特点(其他线程调用):不会开启新线程,执行完一个任务,再执行下一个任务。
     */
    - (void)syncMain {
        //打印当前线程
        NSLog(@"currentThread---%@",[NSThread currentThread]);
        NSLog(@"syncMain---begin");
        dispatch_queue_t queue = dispatch_get_main_queue();
        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(@"syncMain---end");
    }
    运行结果:
    2020-07-06 21:05:31.879924+0800 GCD[16452:3198245] currentThread---<NSThread: 0x6000039819c0>{number = 7, name = (null)}
    2020-07-06 21:05:31.880029+0800 GCD[16452:3198245] syncMain---begin
    2020-07-06 21:05:33.890953+0800 GCD[16452:3198120] 1---<NSThread: 0x6000039eed00>{number = 1, name = main}
    2020-07-06 21:05:35.891477+0800 GCD[16452:3198120] 1---<NSThread: 0x6000039eed00>{number = 1, name = main}
    2020-07-06 21:05:37.902365+0800 GCD[16452:3198120] 2---<NSThread: 0x6000039eed00>{number = 1, name = main}
    2020-07-06 21:05:39.902559+0800 GCD[16452:3198120] 2---<NSThread: 0x6000039eed00>{number = 1, name = main}
    2020-07-06 21:05:41.903112+0800 GCD[16452:3198120] 3---<NSThread: 0x6000039eed00>{number = 1, name = main}
    2020-07-06 21:05:43.903433+0800 GCD[16452:3198120] 3---<NSThread: 0x6000039eed00>{number = 1, name = main}
    2020-07-06 21:05:43.903644+0800 GCD[16452:3198245] syncMain---end
    

    相关文章

      网友评论

          本文标题:同步执行 + 主队列

          本文链接:https://www.haomeiwen.com/subject/qqagqktx.html