Swift GCD詳解

1.延時器

// 主線程調用
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5.0) {
    print("5 秒后輸出", Thread.current.isMainThread)
}
// 5 秒后輸出 true

2.異步執行回主線程寫法

DispatchQueue.global().async {
    print("async do something\(Thread.current)")
    DispatchQueue.main.async {
        print("come back to main thread\(Thread.current)")
    }
}
/*
async do something<NSThread: 0x600002f7e6c0>{number = 3, name = (null)}
come back to main thread<NSThread: 0x600002f27c80>{number = 1, name = main}
*/

3. DispatchGroup(線程組)

let group = DispatchGroup()
// 第一組
group.enter()
AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-500.json", success: { (json) in
    group.leave()
    print("第一組成功")
}) { (error) in
     group.leave()
    print("第一組失敗")
}

// 第二組
group.enter()
AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-10.json", success: { (json) in
    group.leave()
    print("第二組成功")
}) { (error) in
    group.leave()
    print("第二組失敗")
}

// 結束
group.notify(queue: DispatchQueue.main) {
     print("全部執行完成")
}
/*
第二組成功
第一組成功
全部執行完成
*/

4.信號量(DispatchSemaphore)

let semaphore = DispatchSemaphore(value: 1)
let queue = DispatchQueue(label: "L?II")


// 第一組
queue.async {
     semaphore.wait()
    AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-100.json", success: { (json) in
        semaphore.signal()
        print("第一組成功")
    }) { (error) in
        semaphore.signal()
        print("第一組失敗")
    }
}


// 第二組
queue.async {
    semaphore.wait()
    AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-100000.json", success: { (json) in
        semaphore.signal()
        print("第二組成功")
    }) { (error) in
        semaphore.signal()
        print("第二組失敗")
    }
}


// 結束
queue.async {
    semaphore.wait()

    AlamofireTools().getAlamofireData(url: "topic/list/jingxuan/1/bs02-iphone-4.6/0-1.json", success: { (json) in
        semaphore.signal()
        print("全部執行完成")
    }) { (error) in
        semaphore.signal()
        print("全部執行完成")
    }
}
/*
queue.async {
    semaphore.wait()
    DispatchQueue.main.async {
        print("全部執行完成")
        semaphore.signal()
    }
}
*/
/*
第一組成功
第二組成功
全部執行完成
*/
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Swift1> Swift和OC的區別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,145評論 1 32
  • 原文:http://www.lxweimin.com/p/2d57c72016c6[https://www.jia...
    夜雨聲煩_閱讀 427評論 0 0
  • 本文用來介紹 iOS 多線程中 GCD 的相關知識以及使用方法。這大概是史上最詳細、清晰的關于 GCD 的詳細講...
    花花世界的孤獨行者閱讀 525評論 0 1
  • 本文是由于筆者在閱讀有關多線程的文章的時候,看到的覺得寫的很好, 就此記錄下. 在開發 APP 的時候很多時候可能...
    我太難了_9527閱讀 394評論 0 2
  • 本文內容任務、隊列的概念、創建方式任務 + 隊列的6種組合的執行方式線程間如何通信dispatch_once、di...
    小秀秀耶閱讀 1,041評論 0 9