在我們開發(fā)過程中我們經(jīng)常會(huì)用到多線程開發(fā)熊赖,比如在異步線程中加載資源朦蕴,執(zhí)行好使操作等瓶摆,在iOS開發(fā)中常見的多線程操作主要有Thread(NSThread)
凹蜂、Operation(NSOperation)
馍驯、GCD
這幾種方式,我們下面來一一了解這些多線程操作方式玛痊。
Thread
在Objective-C
中為NSThread
這種線程操作方式最多的在我們使用對(duì)象調(diào)用方法時(shí)汰瘫,使用perform(_:on:with:waitUntilDone:modes:)
方法。但是Thread
也可以作為開辟一個(gè)新線程的方式擂煞。
首先我們學(xué)習(xí)它的初始化方法混弥,我們可以通過Selector
或者閉包的方式初始化一個(gè)新方法,然后通過start
方法開啟這個(gè)線程。
// 使用`Selector`方式創(chuàng)建Thread
thread2 = Thread(target: self, selector: #selector(asynExecute(_:)), object: nil)
// 方便調(diào)試蝗拿,添加name
thread2.name = "thread 2"
// 開始執(zhí)行線程
thread2.start()
// 使用閉包方式創(chuàng)建`Thread`
thread1 = Thread {
for i in 0...100 {
// 休眠1秒
Thread.sleep(forTimeInterval: 1)
print("thread 1 \(i)")
print("thread 1 isCanceled \(self.thread1.isCancelled)")
print("thread 1 isExecuting \(self.thread1.isExecuting)")
// 判斷thread2 是否執(zhí)行完畢
if self.thread2.isFinished {
print("thread 2 is finished ")
// 終止thread1
print("current \(Thread.current.name ?? "")")
// 取消當(dāng)前線程晾捏,但是沒有取消循環(huán)執(zhí)行?哀托?惦辛?
self.thread1.cancel()
// 終止當(dāng)前線程執(zhí)行
Thread.exit()
}
}
}
// 方便調(diào)試,添加name
thread1.name = "thread 1"
// 開始執(zhí)行線程
thread1.start()
@objc func asynExecute(_ thread: Thread) {
for i in 0...100 {
// 休眠 0.5s
Thread.sleep(forTimeInterval: 0.5)
print("thread 2 \(i)")
}
}
執(zhí)行上述代碼仓手,我們可以看到結(jié)果胖齐,thread2和thread1交替執(zhí)行。
thread 2 0
thread 1 0
thread 1 isCanceled false
thread 1 isExecuting true
thread 2 1
thread 2 2
thread 1 1
thread 1 isCanceled false
thread 1 isExecuting true
thread 2 3
thread 2 4
......
thread 1 isCanceled false
thread 1 isExecuting true
thread 2 is finished
current thread 1
我們也可以通過集成Thread
來創(chuàng)建一個(gè)線程嗽冒,集成Thread
并重寫main
方法即可呀伙。
class AsyncThread: Thread {
override func main() {
for i in 0 ... 100 {
print(i)
}
}
}
let thread = AsyncThread()
thread.start()
Thread
的用法比較簡(jiǎn)單,我們可以方便的用來開啟線程添坊,當(dāng)然這只是Thread
最基本的用發(fā)剿另,我們也可以通過isMainThread
判斷是否為主線程,更多的方法可以閱讀Thread
相關(guān)文檔帅腌。
更好的閱讀體驗(yàn)可以參考個(gè)人網(wǎng)站:https://zevwings.com