DispatchGroup.wait()和DispatchGroup.notify()区别

wait()会等待线程执行完载执行之后的逻辑,阻塞当前线程

    let myQuenue = DispatchQueue(label: "myQuneue")
    let myGroup = DispatchGroup()
    
    myGroup.enter()
    myQuenue.async {
        Thread.sleep(forTimeInterval: 5)
        print("哈哈哈哈哈哈哈哈哈哈")
        myGroup.leave()
    }
    
    myGroup.enter()
    myQuenue.async {
        Thread.sleep(forTimeInterval: 1)
        print("kkkkkkkk")
        myGroup.leave()
    }
    
    myGroup.wait()
    print("咔咔咔咔咔咔扩扩扩扩扩")
    结果:哈哈哈哈哈哈哈哈哈哈
         kkkkkkkk
         咔咔咔咔咔咔扩扩扩扩扩

notify()不会阻塞当前线程,先执行notify后面的同步方法

    let myQuenue = DispatchQueue(label: "myQuneue")
    let myGroup = DispatchGroup()
    
    myGroup.enter()
    myQuenue.async {
        Thread.sleep(forTimeInterval: 5)
        print("哈哈哈哈哈哈哈哈哈哈")
        myGroup.leave()
    }
    
    myGroup.enter()
    myQuenue.async {
        Thread.sleep(forTimeInterval: 1)
        print("kkkkkkkk")
        myGroup.leave()
    }
    
    myGroup.notify(queue: myQuenue) {
        print("k啦啦啦啦啦啦啦啦")
    }
    print("呜呜呜呜呜呜呜呜无无")
  结果:呜呜呜呜呜呜呜呜无无
       哈哈哈哈哈哈哈哈哈哈
       kkkkkkkk
       咔咔咔咔咔咔扩扩扩扩扩
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。