Swift 多線程的簡單使用

1. Thread

閉包內(nèi)直接執(zhí)行代碼

/// 閉包內(nèi)直接執(zhí)行代碼
Thread.detachNewThread {
                print("111")
}

創(chuàng)建一個方法 開啟子線程后去調(diào)用

//創(chuàng)建一個方法 開啟子線程后去調(diào)用
let tr = Thread(target: self, selector: #selector(threadTest), object: nil)
//開啟
tr.start()

@objc func threadTest () {
        print("777")
}

2. Operation

BlockOperation

/// BlockOperation
let operation = BlockOperation {
      print(" ----- BlockOperation  -----")
}
let queue = OperationQueue()
queue.addOperation(operation)

繼承自 Operation


/// 繼承自 Operation
class MyOperation: Operation {
            override func main() {
                print("--- MyOperation do ... ----")
            }
}
let operation = MyOperation()
/// 當(dāng) operation 執(zhí)行完 會執(zhí)行這個
operation.completionBlock = {
            print("----- completionBlock  ------")
}
let queue = OperationQueue()
queue.addOperation(operation)

3. GCD

隊列 Queue 常用的

// 異步 并行
DispatchQueue.global().async {
            
        }
// 回到主線程異步
DispatchQueue.main.async {
            
        }
// 異步延時
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
            
        }

Queue

label:名字標(biāo)簽
qos:優(yōu)先級
attributes:串行隊列、并行隊列 concurrent
autoreleaseFrequency:頻率


let queue = DispatchQueue(label: "myQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
        
queue.async {
            print(" --- 異步 ---")
        }
        
queue.sync {
            print("--- 同步 -----")
        }
        
queue.asyncAfter(deadline: .now() + 5) {
            print("---- 5s ------")
        }

串行隊列

同步會等待他上一個進(jìn)入的線程執(zhí)行完才會開始(無論上一個線程是同步還是異步),并且阻擋線程等待自己執(zhí)行完畢才會繼續(xù)往下執(zhí)行

/// 串行隊列
let queue = DispatchQueue(label: "myQueue")
let group = DispatchGroup()

print("------- 開始 -------")

group.enter()
queue.async {
    sleep(3)
    print("------- 異步 A -------")
    group.leave()
}


group.enter()
queue.sync {
    print("------- 同步 A -------")
    group.leave()
}
print("------- 同步 A 結(jié)束 -------")


group.enter()
queue.sync {
    print("------- 同步 B -------")
    group.leave()
}
print("------- 同步 B 結(jié)束 -------")


group.enter()
queue.async {
    sleep(1)
    print("------- 異步 B -------")
    group.leave()
}

print("------- 等待 -------")
// wait 會阻塞線程
group.wait()
print("------- 結(jié)束 -------")

// notify 不會阻塞
//group.notify(queue: queue) {
//print("------- 結(jié)束 -------")
//}

------- 開始 -------
------- 異步 A -------
------- 同步 A -------
------- 同步 A 結(jié)束 -------
------- 同步 B -------
------- 同步 B 結(jié)束 -------
------- 等待 -------
------- 異步 B -------
------- 結(jié)束 -------

并行隊列

同步會阻塞后面的線程執(zhí)行,且同步不受前邊異步的影響

let queue = DispatchQueue(label: "myQueue", attributes: DispatchQueue.Attributes.concurrent)
let group = DispatchGroup()

print("------- 開始 -------")

group.enter()
queue.async {
    sleep(1)
    print("------- 異步 A -------")
    group.leave()
}

group.enter()
queue.sync {
    sleep(1)
    print("------- 同步 A -------")
    group.leave()
}
print("------- 同步 A 結(jié)束 -------")

group.enter()
queue.sync {
    sleep(3)
    print("------- 同步 B -------")
    group.leave()
}
print("------- 同步 B 結(jié)束 -------")

group.enter()
queue.async {
    sleep(2)
    print("------- 異步 B 耗時操作 -------")
    group.leave()
}

group.notify(queue: queue) {
    print("------- 全部結(jié)束 -------")
}
print("------- 未被耗時操作阻塞 -------")

------- 開始 -------
------- 同步 A -------
------- 同步 A 結(jié)束 -------
------- 異步 A -------
------- 同步 B -------
------- 同步 B 結(jié)束 -------
------- 未被耗時操作阻塞 -------
------- 異步 B 耗時操作 -------
------- 全部結(jié)束 -------

DispatchSource 定時器例子

var time = 7
let timer = DispatchSource.makeTimerSource(flags: [], queue: .global())
//每秒執(zhí)行一次
timer.schedule(deadline: .now(), repeating: 1)
timer.setEventHandler {
//  由于使用的 queue 是  .global()   這里不是主線程 
    time -= 1
    print("----- \(time)")
    if time == 1 {
        timer.cancel()
    }
}
timer.resume()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容