不废话直接上代码:
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
}
}
网友评论