Swift队列组

应用场景:一个页面有6个请求,请求完毕后统一刷新UI

func initData() -> Void {
        let group = DispatchGroup()
        let queue = DispatchQueue.global()
        
        queue.async(group: group, execute: {
            group.enter()
            
            queue.asyncAfter(deadline: .now() + 4) {
                
                uLog("11111111")
                group.leave()
            }
        })
        queue.async(group: group, execute: {
            group.enter()
            
            queue.asyncAfter(deadline: .now() + 1) {
                
                uLog("222")
                group.leave()
            }
        })
        queue.async(group: group, execute: {
            group.enter()
            
            queue.asyncAfter(deadline: .now() + 6) {
                
                uLog("3333")
                group.leave()
            }
        })
        queue.async(group: group, execute: {
            group.enter()
            
            queue.asyncAfter(deadline: .now() + 10) {
                
                uLog("4444")
                group.leave()
            }
        })
        queue.async(group: group, execute: {
            group.enter()
            uLog("555")
            group.leave()
        })
        
        
        group.notify(queue: queue) {
            uLog("完结咯,刷新UI")
        }
    }

打印结果:
5,2,1,3,4,完结

也可用信号量,感觉没有这样简单

推荐阅读更多精彩内容