在 Swift 中,线程常驻是指创建一个线程,并保持其长期存在,以处理持续的任务或等待事件。
import UIKit
class ViewController: UIViewController {
var thread: Thread!
var port = Port()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.thread = Thread(target: self, selector: #selector(createThread), object: nil)
self.thread.start()
}
@objc func createThread() {
let runLoop = RunLoop.current
runLoop.add(self.port, forMode: .default)
while !Thread.current.isCancelled {
runLoop.run(mode: .default, before: Date.distantFuture)
}
print("Thread is exiting")
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.perform(#selector(runTask), on: thread, with: nil, waitUntilDone: false)
// 5秒后关闭线程
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.perform(#selector(self.cancelThread), on: self.thread, with: nil, waitUntilDone: false)
}
}
@objc func cancelThread() {
Thread.current.cancel()
}
@objc func runTask() {
print("\(Thread.current) New task running")
sleep(1)
print("\(Thread.current) New task completed")
}
}