- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"走!!!");
// 一定注意,不能杀死主线程!
// [NSThread exit];
[self threadDemo];
}
- (void)threadDemo {
// 实例化线程对象(新建)
NSThread *t = [[NSThread alloc] initWithTarget:self selector:@selector(threadStatus) object:nil];
// 线程就绪(被添加到可调度线程池中)
[t start];
}
- (void)threadStatus {
// 阻塞,当运行时满足某一个条件,会让线程"休眠"/锁
// 提示:sleep 方法是类方法,会直接休眠当前线程
NSLog(@"睡会");
// 直接睡两秒
[NSThread sleepForTimeInterval:2.0];
for (int i = 0; i < 20; i++) {
if (i == 8) {
// 线程执行中,满足某一个条件时,再次休眠
NSLog(@"再睡会");
// 睡到指定的日期,从现在开始过了多久
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
}
NSLog(@"%@ %d", [NSThread currentThread], i);
// 当线程满足某一个条件时,可以强行终止
if (i == 15) {
// 一旦强行终止线程,后续的所有代码都不会被执行
// 注意:在终止线程之前,应该注意释放之前分配的对象!
// 如果是 ARC 开发,需要注意,清理 C 语言框架创建的对象!否则会出现内存泄漏!
[NSThread exit];
}
}
NSLog(@"能来吗?");
}
NSThread—线程状态
最新推荐文章于 2022-02-21 09:14:14 发布