【发布时间】:2016-12-13 17:29:36
【问题描述】:
我想模拟与服务器的通信。由于远程服务器会有一些延迟,我想使用它上面的后台线程
[NSThread sleepForTimeInterval:timeoutTillAnswer];
线程是使用 NSThread 子类创建并启动的……但是我注意到 sleepForTimeInterval 阻塞了主线程……为什么??? NSThread 默认不是 backgroundThread 吗?
线程是这样创建的:
self.botThread = [[PSBotThread alloc] init];
[self.botThread start];
更多信息: 这是机器人线程子类
- (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:(它会在调用它时延迟当前线程)。 -
这就是我创建线程的方式... [self.botThread start]; ...调用 NSThread 子类 PSBotThread main 方法 .. .
-
但是它有什么作用呢?
sleepForTimeInterval在哪里? -
线程使用一个对象来接收消息并返回一个结果...... sleepForTimeInterval 在这个对象内