我有下一个代码:
private var timer: dispatch_source_t?
private let queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL)
private func startTimer() {
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
dispatch_source_set_timer(timer!, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC)
dispatch_source_set_event_handler(timer!) {
self.process()
}
dispatch_resume(timer!)
}
private func stopTimer() {
if timer != nil {
dispatch_source_cancel(timer!)
timer = nil
}
}
public func callNow() {
dispatch_async(queue, {self.process()})
}
private func process() {
Log.d(tag, message: "process currentThread=\(NSThread.currentThread())")
}
为什么我在两个不同的线程中调用process
方法?
process currentThread=<NSThread: 0x7f8080e01880>{number = 2, name = (null)}
process currentThread=<NSThread: 0x7f8080e03d40>{number = 3, name = (null)}
process currentThread=<NSThread: 0x7f8080e03d40>{number = 3, name = (null)}
process currentThread=<NSThread: 0x7f8080e03d40>{number = 3, name = (null)}
答案 0 :(得分:2)
不要将线程与操作队列混淆。一个操作队列中的任务在不同的线程上执行是完全正常的。来自Apple's documentation:
串行队列(也称为专用调度队列)按照将它们添加到队列的顺序一次执行一个任务。当前正在执行的任务在由调度队列管理的不同线程(可能因任务而异)上运行。串行队列通常用于同步对特定资源的访问。