取消线程的执行

  • cancel:方法仅仅是给线程标记为取消状态。但是要想真正取消线程的执行,必须在线程内部判断

//打上取消标识



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 创建线程 -- 新建状态
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo) object:nil];
    // 将线程添加到可调度线程池中,等等CPU调度
    [thread start];
    // 睡会
    [NSThread sleepForTimeInterval:1.2];
    // 取消线程
    // cancel:方法仅仅是给线程标记为取消状态。但是要想真正取消线程的执行,必须在线程内部判断。
    [thread cancel];
}
  • 在关键时刻取消
// 一个方法内部的代码是在同一个线程中执行的
- (void)demo {
    NSLog(@"睡会 = %@",[NSThread currentThread]);
    if ([NSThread currentThread].isCancelled) {
        NSLog(@"1...88");
        return;
    }
    [NSThread sleepForTimeInterval:1.0];
    // 在关键节点判断线程是否被取消
    if ([NSThread currentThread].isCancelled) {
        NSLog(@"2...88");
        return;
    }
    for (NSInteger index = 0; index < 20; index ++) {
        if ([NSThread currentThread].isCancelled) {
            NSLog(@"3...88");
            return;
        }
        // 在满足某个条件的时候,再睡
        if (index == 10) {
            NSLog(@"再睡");
            // 睡到指定的时间
            [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
        }
        NSLog(@"%@--%zd",[NSThread currentThread],index);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值