NSThread sleepfortimeinterval阻止主线程

我想模拟与服务器的通信。 由于远程服务器将有一些延迟,我想使用它的背景线程

[NSThread sleepForTimeInterval:timeoutTillAnswer]; 

线程创build与NSThread子分类,并开始…但是,我注意到sleepForTimeInterval阻止主线程…为什么? 是不是NSThread默认情况下backgroundThread?

这是如何创build线程:

  self.botThread = [[PSBotThread alloc] init]; [self.botThread start]; 

更多信息:这是bot线程子程序

 - (void)main { @autoreleasepool { self.gManager = [[PSGameManager alloc] init]; self.comManager = [[PSComManager alloc] init]; self.bot = [[PSBotPlayer alloc] initWithName:@"Botus" andXP:[NSNumber numberWithInteger:1500]]; self.gManager.localPlayer = self.bot; self.gManager.comDelegate = self.comManager; self.gManager.tillTheEndGame = NO; self.gManager.localDelegate = self.bot; self.comManager.gameManDelegate = self.gManager; self.comManager.isBackgroundThread = YES; self.comManager.logginEnabled = NO; self.gManager.logginEnabled = NO; self.bot.gameDelegate = self.gManager; BOOL isAlive = YES; // set up a run loop NSRunLoop *runloop = [NSRunLoop currentRunLoop]; [runloop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; [self.gManager beginGameSP]; while (isAlive) { // 'isAlive' is a variable that is used to control the thread existence... [runloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } } } - (void)messageForBot:(NSData *)msg { [self.comManager didReceiveMessage:msg]; } 

我想从主线程调用“messageForBot”…后台线程也应该调用主线程上的一个方法进行通信。睡眠时间在gManager对象内部进行间歇….

它阻塞sleepForTimeInterval正在运行的任何线程。 在另一个线程上运行它来模拟你的服务器延迟,如下所示:

 dispatch_queue_t serverDelaySimulationThread = dispatch_queue_create("com.xxx.serverDelay", nil); dispatch_async(serverDelaySimulationThread, ^{ [NSThread sleepForTimeInterval:10.0]; dispatch_async(dispatch_get_main_queue(), ^{ //Your server communication code here }); }); 

尝试在您的线程类中创build一个名为sleepThread的方法

 -(void)sleepThread { [NSThread sleepForTimeInterval:timeoutTillAnswer]; } 

然后让它从你的主线程中睡觉

 [self.botThread performSelector:@selector(sleepThread) onThread:self.botThread withObject:nil waitUntilDone:NO]; 

发送更新到您的主线程从您的机器人线程。

 dispatch_async(dispatch_get_main_queue(), ^{ [MainClass somethinghasUpdated]; }); 

边注

要创buildRunLoop,我认为你需要做的就是

 // Run the Current RunLoop [[NSRunLoop currentRunLoop] run]; 

迅速:

 let nonBlockingQueue: dispatch_queue_t = dispatch_queue_create("nonBlockingQueue", DISPATCH_QUEUE_CONCURRENT) dispatch_async(nonBlockingQueue) { NSThread.sleepForTimeInterval(1.0) dispatch_async(dispatch_get_main_queue(), { // do your stuff here }) }