顺便说一下,这段代码在 NSThread 选择器中. 解决方案 如果你想简单地做,用类似于 Java 的语法只是为了不要混淆,那就是这样做的方法:@synchronized(uploadWorkerLock){usleep(UPLOAD_WORKER_SLEEP_TIME*1000);}但这不是唯一的方法,@synchronized 指令不如自旋锁或 NSLock 快.另一种方法是 GCD,它允许您可以同时(虚拟地)执行一些代码块.它比使用单独的线程更快,因为它会尝试优化事物,并且它可以在同一线程中运行两个单独的代码块,只需模拟多线程,从而避免代价高昂的上下文交换.此外,使用 GCD 做到这一点并不难,但是它需要一些额外的块知识,而这对于刚开始使用 Objective-C 的人来说可能有点混乱.此外,GCD 不能替代多线程,当您有一个复杂的应用程序并且每个线程不只是执行单个代码块时,纯多线程将更合适.I'm developing an iOS 5.0+ app with latest SDK.This app is a migration from an Android app.On the Android app I have this code:private Object uploadWorkerLock = new Object();private static final int UPLOAD_WORKER_SLEEP_TIME = 30000;[ ... ]synchronized (ServerManager.this.uploadWorkerLock) { try { ServerManager.this.uploadWorkerLock.wait(UPLOAD_WORKER_SLEEP_TIME); } catch (InterruptedException e) { return; }}I've a problem with void java.lang.Object.wait(long millis). I can migrate that code this way:NSCondition* uploadWorkerLock;[ ... ][uploadWorkerLock lock];[uploadWorkerLock wait];[uploadWorkerLock unlock];Reading Java documentation about wait(long), I have read this:Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.I know I can invoke [uploadWorkerLock invoke] but how can I simulate that the specified amount of time has elapsed.?By the way, this code is inside of a NSThread selector. 解决方案 If you want to do it simply, with a syntax similar to Java just to don't get confused, that's how to do it: @synchronized(uploadWorkerLock){ usleep(UPLOAD_WORKER_SLEEP_TIME*1000);}But this isn't the only way, the @synchronized directive isn't as fast as spin locks, or a NSLock. Another way is GCD, which allows you to execute some blocks of code (virtually) at the same time. It is faster than using separate threads, because it will try to optimize things, and it can run two separated blocks of code in the same thread, just simulating multithreading so avoiding context swapping which is expensive.Also with GCD it isn't hard to do it, but it requires some additional knowledge of blocks and things that can be a bit messy for who just started with Objective-C. Also, GCD isn't a substitute for multithreading, when you have a complex application and every thread doesn't just execute a single block of code, plain multithreading will be more proper. 这篇关于NSCondition:等待指定的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
06-16 08:24