在下面显示的代码中,我创建了一个线程,它创建 0 到 15 之间的随机数,并在它出现 3 时停止,更改结束参数。在我向主线程的运行循环中添加了一个运行循环观察者(即“观察”结束参数)之后。如您所见,运行循环观察者和我的线程在打印前都休眠了 1 秒,所以我希望在控制台中,观察者的打印和我的线程的打印是交替的。事实并非如此。我相信,如果我理解它,它将取决于CFrunloopActivity
参数及其可能的组合。
谁能解释一下这个参数的操作?如果是,是否有交替打印的组合?如果你不能有交替打印,观察者如何在主线程的运行循环中工作?
谢谢
这是代码:
class ViewController: UIViewController {
var end = false
override func viewDidLoad() {
super.viewDidLoad()
//my thread
performSelector(inBackground: #selector(rununtil3(thread:)), with: Thread.current)
//the observer
let runLoopObserver = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFRunLoopActivity.entry.rawValue | CFRunLoopActivity.exit.rawValue , true , 0 , {
(observer: CFRunLoopObserver?, activity: CFRunLoopActivity) -> Void in
Thread.sleep(until: Date(timeIntervalSinceNow: 1))
print("+++ is main?: \(Thread.isMainThread)")
if self.end == true {
//print the end of my thread and remove the observer from main run loop
print("end of own thread")
CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), observer, CFRunLoopMode.commonModes)
return
}
//CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), observer, CFRunLoopMode.commonModes)
})
//add observer to main run loop
CFRunLoopAddObserver(CFRunLoopGetCurrent(), runLoopObserver, CFRunLoopMode.commonModes)
print("Out of observer")
}
func rununtil3(thread : Thread) {
print("main?: \(thread.isMainThread) is run : \(thread.isExecuting)")
while true {
let ran = Int (arc4random() % 15 )
Thread.sleep(until: Date(timeIntervalSinceNow: 1))
print("\(ran) . main is run : \(thread.isExecuting)")
if ran == 3 {
end = true
Thread.exit()
}
}
}
}