iOS多线程——Thread(Swift版)
1. 概述
线程是非常有用的,当执行一个比较耗时的操作,但是又不想影响到主线程的时候,这个时候就需要多线程了,从而提高应用程序的性能,增强用户体验。
本篇文章将讲述iOS多线程中的一种Thread
,下面来具体看一下。
作为一个开发者,有一个学习的氛围跟一个交流圈子特别重要,这是一个我的iOS交流群:812157648,不管你是小白还是大牛欢迎入驻 ,分享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 | Thread | 返回当前线程对象。 |
class var isMainThread: Bool | Bool | 当前线程是否为主线程。 |
class var main: Thread | Thread | 返回主线程对象。 |
var threadPriority: Double | Double | 线程优先级,取值范围0.0~1.0,默认0.5,值越高优先级越高 |
var name: String? | String | 线程名称。 |
var isMainThread: Bool | Bool | 线程是否为主线程。 |
var isExecuting: Bool | Bool | 线程是否正在执行。 |
var isFinished: Bool | Bool | 线程是否已经结束。 |
var isCancelled: Bool | 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