美文网首页
【iOS】GCD 2个队列 插队

【iOS】GCD 2个队列 插队

作者: SmartGao | 来源:发表于2017-04-25 10:57 被阅读0次

    线程lineOne 执行任务期间,让lineTwo任务执行后,再执行剩下的lineOne任务。

    //  Created by SmartGao on 17/4/25.
    //  Copyright © 2017年 gc. All rights reserved.
    //
    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @property (nonatomic, strong) dispatch_queue_t lineOne;
    @property (nonatomic, strong) dispatch_queue_t lineTwo;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
       
        // DISPATCH_QUEUE_SERIAL 串行队列
        _lineOne = dispatch_queue_create("test.lineOne", DISPATCH_QUEUE_SERIAL);
        _lineTwo = dispatch_queue_create("test.lineTwo", DISPATCH_QUEUE_SERIAL);
        
        // 使用dispatch_set_target_queue()实现队列的动态调度管理
        dispatch_set_target_queue(_lineOne, _lineTwo);
        
        for (NSInteger i = 0; i < 20; i++) {
            dispatch_async(_lineOne, ^{
                [NSThread sleepForTimeInterval:1.0];
                NSLog(@"lineOne: %ld ",i);
            });
        }
        
        dispatch_async(_lineOne, ^{
            NSLog(@"全部完成 ");
        });
        
    }
    
    - (IBAction)buttonAction:(id)sender {
        // 这时则只会暂停dispatchA上原来的block的执行,dispatchB的block则不受影响。而如果暂停dispatchB的运行,则会暂停dispatchA的运行。
        dispatch_suspend(_lineOne);
        dispatch_async(_lineTwo, ^{
            NSLog(@"lineTwo插队!!");
            dispatch_resume(_lineOne);
        });
        
    }
    

    相关文章

      网友评论

          本文标题:【iOS】GCD 2个队列 插队

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