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

异步执行 + 主队列

作者: Jean_Lina | 来源:发表于2020-07-06 21:16 被阅读0次
/**
 * 异步执行 + 主队列
 * 特点:只在主线程中执行任务,执行完一个任务,再执行下一个任务
 */
- (void)asyncMain {
    //打印当前线程
    NSLog(@"currentThread---%@",[NSThread currentThread]);
    NSLog(@"asyncMain---begin");
    dispatch_queue_t queue = dispatch_get_main_queue();
    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(@"asyncMain---end");
}

//Swift版本
func asyncThread() {
        DispatchQueue.global().async {
            DNPrint("异步开启一条线程: \(Thread.current)")
        }
        DispatchQueue.main.async {
            DNPrint("回到主线程: \(Thread.current)")
        }
}
运行结果:
2020-07-06 21:15:49.605622+0800 GCD[16675:3267947] currentThread---<NSThread: 0x6000030e2d00>{number = 1, name = main}
2020-07-06 21:15:49.605769+0800 GCD[16675:3267947] asyncMain---begin
2020-07-06 21:15:49.605878+0800 GCD[16675:3267947] asyncMain---end
2020-07-06 21:15:51.617289+0800 GCD[16675:3267947] 1---<NSThread: 0x6000030e2d00>{number = 1, name = main}
2020-07-06 21:15:53.617897+0800 GCD[16675:3267947] 1---<NSThread: 0x6000030e2d00>{number = 1, name = main}
2020-07-06 21:15:55.618071+0800 GCD[16675:3267947] 2---<NSThread: 0x6000030e2d00>{number = 1, name = main}
2020-07-06 21:15:57.618964+0800 GCD[16675:3267947] 2---<NSThread: 0x6000030e2d00>{number = 1, name = main}
2020-07-06 21:15:59.620010+0800 GCD[16675:3267947] 3---<NSThread: 0x6000030e2d00>{number = 1, name = main}
2020-07-06 21:16:01.621313+0800 GCD[16675:3267947] 3---<NSThread: 0x6000030e2d00>{number = 1, name = main}

相关文章

网友评论

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

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