iOS多執行緒——Thread(Swift版)
阿新 • • 發佈:2020-12-12
1. 概述
執行緒是非常有用的,當執行一個比較耗時的操作,但是又不想影響到主執行緒的時候,這個時候就需要多執行緒了,從而提高應用程式的效能,增強使用者體驗。
本篇文章將講述iOS多執行緒中的一種Thread
,下面來具體看一下。
作為一個開發者,有一個學習的氛圍跟一個交流圈子特別重要,這是一個我的iOS交流群:196800191,加群密碼:112233,不管你是小白還是大牛歡迎入駐 ,分享BAT,阿里面試題、面試經驗,討論技術, 大家一起交流學習成長!
2. Thread的建立
@available(iOS 2.0, *) public convenience init(target: Any, selector: Selector, object argument: Any?) @available(iOS 10.0, *) public convenience init(block: @escaping () -> Void) @available(iOS 10.0, *) open class func detachNewThread(_ block: @escaping () -> Void) open class func detachNewThreadSelector(_ selector: Selector, toTarget target: Any, with argument: Any?)
上面的方法中,前兩個是物件的初始化方法,返回一個Thread物件,而後兩個則是類方法,直接開啟了一個子執行緒。
下面看一組測試:
func createThread() { let thread1 = Thread(target: self, selector: #selector(threadMethod1), object: nil) let thread2 = Thread { print("thread2 \(Thread.current)") } thread1.start() thread2.start() Thread.detachNewThreadSelector(#selector(threadMethod3), toTarget: self, with: nil) Thread.detachNewThread { print("thread4 \(Thread.current)") } } @objc func threadMethod1() { print("thread1 \(Thread.current)") } @objc func threadMethod3() { print("thread3 \(Thread.current)") }
執行後得到:
thread4 <NSThread: 0x600002284600>{number = 9, name = (null)}
thread2 <NSThread: 0x600002284540>{number = 7, name = (null)}
thread1 <NSThread: 0x600002284500>{number = 6, name = (null)}
thread3 <NSThread: 0x600002284580>{number = 8, name = (null)}
通過初始化物件得到的Thread物件,需要呼叫start()方法來開啟子執行緒,即將該子執行緒設定為就緒的狀態,等待CPU的排程。
而通過類方法開闢的兩個子執行緒,不返回Thread物件,建立後即就緒狀態,無需start()方法。
3. Thread常用屬性及方法
常見屬性列表:
屬性名稱 | 型別 | 描述 |
---|---|---|
class var current: Thread { get } | Thread | 返回當前執行緒物件。 |
class var isMainThread: Bool { get } | Bool | 當前執行緒是否為主執行緒。 |
class var main: Thread { get } | Thread | 返回主執行緒物件。 |
var threadPriority: Double | Double | 執行緒優先順序,取值範圍0.0~1.0,預設0.5,值越高優先順序越高 |
var name: String? | String | 執行緒名稱。 |
var isMainThread: Bool { get } | Bool | 執行緒是否為主執行緒。 |
var isExecuting: Bool { get } | Bool | 執行緒是否正在執行。 |
var isFinished: Bool { get } | Bool | 執行緒是否已經結束。 |
var isCancelled: Bool { get } | Bool | 執行緒是否已標記為取消。 |
常見類方法及例項方法列表:
方法名稱 | 返回值型別 | 描述 |
---|---|---|
class func isMultiThreaded() -> Bool | Bool | 是否是多執行緒。 |
class func sleep(until date: Date) | Void | 執行緒阻塞到某一時間。 |
class func sleep(forTimeInterval ti: TimeInterval) | Void | 執行緒阻塞一段時間。 |
class func exit() | Void | 退出當前執行緒,不可在主執行緒呼叫,否則程式崩潰。 |
class func threadPriority() -> Double | Double | 獲取執行緒優先順序。 |
class func setThreadPriority(_ p: Double) -> Bool | Bool | 設定執行緒優先順序,取值範圍0.0~1.0,預設0.5,值越高優先順序越高。 |
func cancel() | Void | 將執行緒標記為取消狀態。 |
func start() | Void | 開啟執行緒。 |
4. Thread常用屬性及方法示例
override func viewDidLoad() {
super.viewDidLoad()
// 設定主執行緒名稱
Thread.main.name = "MainThread"
threadTestDemo()
}
func threadTestDemo() {
// 建立子執行緒
myThread = Thread(target: self, selector: #selector(myThreadMethod), object: nil)
// 設定子執行緒名稱
myThread?.name = "MyThread"
// 設定子執行緒優先順序
myThread?.threadPriority = 1.0
// 開啟子執行緒
myThread?.start()
// 主執行緒阻塞3秒
Thread.sleep(forTimeInterval: 3)
// 列印子執行緒執行狀態
if let thread = myThread {
print("3 seconds later, myThread is executing : \(thread.isExecuting)")
print("3 seconds later, myThread is finished : \(thread.isFinished)")
}
}
// 子執行緒方法
@objc func myThreadMethod() {
// 列印主執行緒
print("Main thread is : \(Thread.main)")
// 列印當前執行緒
print("Current thread is : \(Thread.current)")
// 判斷當前執行緒是否是主執行緒
print("Current thread is main thread : \(Thread.isMainThread)")
if let thread = myThread {
// 列印子執行緒名稱
print("myThread name is : \(String(describing: thread.name))")
// 列印子執行緒優先順序
print("myThread priority is : \(thread.threadPriority)")
// 列印子執行緒是否是主執行緒
print("myThread is main thread : \(thread.isMainThread)")
// 子執行緒是否正在執行
print("myThread is executing : \(thread.isExecuting)")
// 子執行緒是否標記取消
print("myThread is cancelled : \(thread.isCancelled)")
// 子執行緒是否已經結束。
print("myThread is finished : \(thread.isFinished)")
}
/*
// 在子執行緒中新增一個定時器
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
print("Timer is running")
}
// 預設子執行緒的runloop是不開啟的,如果不開啟,timer無法執行,所以這裡需要手動開啟。
RunLoop.current.run()
*/
}
上面子執行緒方法中註釋了Timer的方法,其執行結果如下:
Main thread is : <NSThread: 0x600000d80400>{number = 1, name = MainThread}
Current thread is : <NSThread: 0x600000dcd040>{number = 7, name = MyThread}
Current thread is main thread : false
myThread name is : Optional("MyThread")
myThread priority is : 1.0
myThread is main thread : false
myThread is executing : true
myThread is cancelled : false
myThread is finished : false
3 seconds later, myThread is executing : false
3 seconds later, myThread is finished : true
上面結果中:3秒後子執行緒執行結束。
如果將Timer註釋程式碼開啟後,執行後結果如下:
Main thread is : <NSThread: 0x600002c6c980>{number = 1, name = MainThread}
Current thread is : <NSThread: 0x600002c5f000>{number = 7, name = MyThread}
Current thread is main thread : false
myThread name is : Optional("MyThread")
myThread priority is : 1.0
myThread is main thread : false
myThread is executing : true
myThread is cancelled : false
myThread is finished : false
Timer is running
Timer is running
Timer is running
3 seconds later, myThread is executing : true
3 seconds later, myThread is finished : false
Timer is running
Timer is running
兩次的執行結果在於3秒後執行緒是否還在執行。
5. NSObject關於Thread的擴充套件方法
一些NSObject關於Thread的擴充套件方法:
open func performSelector(onMainThread aSelector: Selector, with arg: Any?, waitUntilDone wait: Bool, modes array: [String]?)
open func performSelector(onMainThread aSelector: Selector, with arg: Any?, waitUntilDone wait: Bool)
open func perform(_ aSelector: Selector, on thr: Thread, with arg: Any?, waitUntilDone wait: Bool, modes array: [String]?)
open func perform(_ aSelector: Selector, on thr: Thread, with arg: Any?, waitUntilDone wait: Bool)
open func performSelector(inBackground aSelector: Selector, with arg: Any?)
6. 結束語
Thread是iOS中一個比較輕量級的多執行緒方法,使用起來也比較簡單,另外還有兩種主要的多執行緒方法GCD和Operation,後續文章將會依次介紹這兩個,敬請關注哦!
原文作者:Daniel_Coder
原文地址:https://blog.csdn.net/guoyongming925/article/details/109459607