- 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);
}
}