iOS条件锁保活线程

2022-05-27  本文已影响0人  iOS虞

不废话直接上代码:

class ViewController: UIViewController {
      //创建条件锁
      var conditionLock = NSCondition()
      //执行任务
      var executeTask:(() -> Void)!
      //是否停止
      var isStop = false

      override func viewDidLoad() {
        super.viewDidLoad()

        let thread = Thread(block: {
            repeat {
                self. conditionLock.lock()
                if self.executeTask != nil {
                    self.executeTask?()
                    self.executeTask = nil
                }
                self. conditionLock.wait()
                self. conditionLock.unlock()
            } while !self.isStop
        })

        thread.start()
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
        executeTask = {
            //要执行的任务
            print("-------\(Thread.current)")
        }
    }
    //停止
    func stop() {
        conditionLock.signal()
        isStop = true
    }
}
上一篇 下一篇

猜你喜欢

热点阅读