NSThread注意点

如果要停止子线程,有两种方法:
第一种,是在子线程中执行:

[NSThread exit];

另一种是在主线程执行:
[cpp]
[myThread cancel];  
要注意的是,[mThread cancel]; 并不能exit线程,只是标记为canceled,但线程并没有死掉。加入你在子线程中执行了一个循环,则cancel后,循环还在继续,你需要在循环的 条件判断中加入 !mThread.isCancelled 来判断子线程是否已经被cancel来决定是否继续循环。

 

/**
     4.取消线程
     */
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadMethod4) object:nil];
    [thread start];
    
    
    //3秒后终止
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //取消
        [thread cancel];
    });
- (void)threadMethod4
{
    while (1)
    {
        //线程休眠(单位是秒)
        [NSThread sleepForTimeInterval:1];
        
        //判断线程是否是取消状态
        if ([NSThread currentThread].isCancelled)
        {
            //退出线程
            [NSThread exit];
        }
        
        NSLog(@"--------------");
    }
}

 

转载于:https://www.cnblogs.com/zhangjiayi/p/5083507.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值