9

我在主线程中使用 NSThread 创建了一个子线程

NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(MyThread:) object:timer];

5 秒后,我在主线程中使用 [newThread cancel] 来停止子线程,但它没有工作,

方法 MyThread:在 newThread 中仍然有效

那么,停止 newThread 的正确答案是什么,THX

实际上 [newThread isCancelled] 是 YES,但选择器 MyThread 仍在工作

4

2 回答 2

11

cancel方法仅通知线程它已被取消(正如您提到的将更isCancelled改为YES。然后线程本身负责检查并退出。例如,在您的MyThread:方法中,您可以这样做:

// At some checkpoint
if([[NSThread currentThread] isCancelled]) {
    /* do some clean up here */
    [NSThread exit];
}

您应该定期进行此检查,并从线程内退出,如图所示;否则cancel没有任何效果。

于 2010-07-07T02:14:21.360 回答
2

-(无效)取消

讨论 该方法的语义与用于 NSOperation 对象的语义相同。此方法在接收器中设置状态信息,然后由 isCancelled 方法反映。支持取消的线程应该定期调用 isCancelled 方法来确定线程是否实际上已经被取消,如果已经取消则退出。

更多信息请参阅NSThread API 参考

于 2010-10-05T13:46:55.987 回答