iOS 多线程开发之 Thread

129 阅读1分钟

iOS 多线程开发之系列文章

iOS 多线程开发之概念

iOS 多线程开发之 Thread

iOS 多线程开发之 GCD

iOS 多线程开发之 Operation

iOS 多线程开发之线程安全

多线程开发是日常开发任务中不可缺少的一部分,在 iOS 开发中常用到的多线程开发技术有 GCD、OperationThread,本文主要讲解多线系列文章中关于 Thread 的相关知识和使用详解。

简介

Thread 比 GCD、Operation 更轻量级,但是需要我们自行管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销。

Thread 的创建

类方法创建线程

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // MARK: 使用类方法
        // 方法一
        Thread.detachNewThreadSelector(#selector(threadMethods1), toTarget:self, with: nil)
        // 方法二
        Thread.detachNewThread {
            print("通过闭包形式")
            print("\(#function):\(Thread.current)")
        }
    }

    // MARK: Target Methods
    @objc private func threadMethods1() {
        print("通过方法形式")
        print("\(#function):\(Thread.current)")
    }
}

注意:无法对线程进行更详细的设置

实例方法创建线程

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // MARK:使用实例方法
        // 方法一
        let thread1 = Thread(target: self, selector: #selector(threadMethods1), object: nil)
        thread1.name = "thread1"
        thread1.threadPriority = 0.5 ///优先级
        thread1.start()
        // 方法二
        let thread2 = Thread{
            print("通过闭包形式")
            print("\(#function):\(Thread.current)")
        }
        thread1.name = "thread2"
        thread1.threadPriority = 1 ///优先级
        thread2.start()
    }

    // MARK:Target Methods
    @objc private func threadMethods1() {
        print("通过方法形式")
        print("\(#function):\(Thread.current)")
    }
}

隐式创建并启动线程

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // MARK:使用 NSObject 拓展方法
        // 在后台执行
        self.performSelector(inBackground:#selector(threadMethods1), with: nil)
        // 在主线程执行
        self.performSelector(onMainThread: #selector(threadMethods1), with: nil, waitUntilDone: false)
    }

    // MARK: Target Methods
    @objc private func threadMethods1() {
        print("通过方法形式")
        print("\(#function):\(Thread.current)")
    }
}