NSThread,停止并等待2秒
问题描述:
我明确创建了一个带NSThread类的工作线程。NSThread,停止并等待2秒
NSThread *workerThread = [[NSThread alloc] initWithTarget:self
selector:@selector(doWork)
object:nil];
[workerThread start];
我知道有在NSThread没有“加入”功能,是什么阻止这个线程&等待2秒钟线程死亡的最好方法? (像Java线程join(2000)功能)
[workerThread cancel]
//how to wait for 2 seconds for the thread to die? I need something like join(2000) in Java
(请不要说话GCD,我的问题是关于NSThread,谢谢。)
答
回采程序线程是不是一个好主意恕我直言,如果可能的话,不知道苹果那样的,但你可以得到一个解决办法...
我看到了这样的方式:
1 /快速和肮脏的NSTimer将检查每一个X秒线程的状态,不是我的杯子的茶虽然。
2 /在你的doWork选择职位时的作业做了NSNotification,并注册它,当它发射了,你知道你的线程完成...
我爱2号更好的解决方案,是的,所以这里GCD ROX是我怎么会做:
static NSThread * workerThread;
- (void) startWorkerThread
{
workerThread = [[NSThread alloc] initWithTarget:self selector:@selector(doWork) object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(workerThreadDidReturn) name:@"workerThreadReturnsNotification" object:nil];
[workerThread start];
static NSInteger timeoutSeconds = 5;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeoutSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// Cancel after timeoutSeconds seconds if not finished yet
if(![workerThread isCancelled]){
[workerThread cancel];
}
});
}
- (void) doWork
{
// Do something heavy...
id result = [NSObject new];
[[NSNotificationCenter defaultCenter] postNotificationName:@"workerThreadReturnsNotification"
object:result];
}
- (void) workerThreadDidReturn:(NSNotification *)notif
{
id result = (id) notify.object;
// do something with result...
[workerThread cancel];
}
什么这个问题:http://stackoverflow.com/questions/7952653/sleep-or-pause-nsthread? – flashspys
@flashspys,显然这个链接与我的问题无关。它谈到让线程睡眠,我的问题是关于等待线程被杀死。如果您检查我的问题中链接的Java join()函数的文档,您将了解我需要的内容。 –
我读过“死去”了,对不起。我认为没有使用gcd或NSOperationQueue是不可能的。 NSThread的API不是很广泛。 – flashspys