Swift学习之多线程

作者: coderhlt | 来源:发表于2020-04-01 10:56 被阅读0次

    一、异步

    class ViewController: UIViewController {
      override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
        DispatchQueue.global().async {
            print("开启子线程:\(Thread.current)")
            }
            DispatchQueue.main.async {
                print("回归主线程:\(Thread.current)")
            }
        }
    }
    
        class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad(
        let dispatchWorkitem = DispatchWorkItem {
                print("创建一个异步任务")
            }
            DispatchQueue.global().async(execute: dispatchWorkitem)
            dispatchWorkitem.notify(queue: DispatchQueue.main) {
                print("回到主线程")
            }
        }
    }
    

    二、延迟执行

         let dispatchWorkitem = DispatchWorkItem {
                print("创建一个异步任务")
            }
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+3, execute: dispatchWorkitem)
            dispatchWorkitem.notify(queue:DispatchQueue.main) {
                print("回归主线程")
            }
    

    三、多线程-once

    dispatch_once在Swift中已经被废弃,可以用类型属性或者全局变量\常量,默认自带lazy + dispatch_once 效果

    fileprivate let task1:Void = {
        print("执行一次")
    }()
    
    class ViewController: UIViewController {
        static var age:Int = {
            print("once")
            return 10
        }()
        override func viewDidLoad() {
            super.viewDidLoad()
           
            let _ = task1
            let _ = task1
            
            let _ = Self.age
            let _ = Self.age
        }
    }
    

    相关文章

      网友评论

        本文标题:Swift学习之多线程

        本文链接:https://www.haomeiwen.com/subject/gekguhtx.html