// MARK: NSObject 的分类方法演练
- (void)threadDemo4 {
Person *p = [Person personWithDict:@{@"name": @"zhangsan"}];
// 主线程执行
// [p loadData];
// 后台线程执行
// performSelectorInBackground 可以让任意一个 NSObject 都具有在后台执行线程的能力!
// 会让代码写起来非常灵活!
[p performSelectorInBackground:@selector(loadData) withObject:nil];
}
// MARK: NSThread 演练
- (void)threadDemo3 {
// 是 "NSObject" 的一个分类方法
// 没有 thread 的"字眼",确实可以开启后台线程,执行 selector 方法
// "隐式"的多线程方法!跟 detach 类方法类似,可以直接开启线程执行方法!
[self performSelectorInBackground:@selector(longOperation:) withObject:@"perform"];
// 1! 同样不会开启线程
NSLog(@"after %@", [NSThread currentThread]);
}
- (void)threadDemo2 {
// 1
NSLog(@"%@", [NSThread currentThread]);
// detach -> "分离"
// 直接新建线程,并且执行 @selector 方法
[NSThread detachNewThreadSelector:@selector(longOperation:) toTarget:self withObject:@"DETACH"];
// 1/2
NSLog(@"after %@", [NSThread currentThread]);
}
- (void)threadDemo1 {
NSLog(@"before %@", [NSThread currentThread]);
// 实例化一个 NSThread 对象
NSThread *t1 = [[NSThread alloc] initWithTarget:self selector:@selector(longOperation:) object:@"NSThread"];
// 启动线程
[t1 start];
// 1/2
NSLog(@"after %@", [NSThread currentThread]);
}
// 耗时操作
- (void)longOperation:(id)obj {
for (int i = 0; i < 10; ++i) {
NSLog(@"%@ %d -- %@", [NSThread currentThread], i, obj);
}
}
- (void)threadDemo4 {
Person *p = [Person personWithDict:@{@"name": @"zhangsan"}];
// 主线程执行
// [p loadData];
// 后台线程执行
// performSelectorInBackground 可以让任意一个 NSObject 都具有在后台执行线程的能力!
// 会让代码写起来非常灵活!
[p performSelectorInBackground:@selector(loadData) withObject:nil];
}
// MARK: NSThread 演练
- (void)threadDemo3 {
// 是 "NSObject" 的一个分类方法
// 没有 thread 的"字眼",确实可以开启后台线程,执行 selector 方法
// "隐式"的多线程方法!跟 detach 类方法类似,可以直接开启线程执行方法!
[self performSelectorInBackground:@selector(longOperation:) withObject:@"perform"];
// 1! 同样不会开启线程
NSLog(@"after %@", [NSThread currentThread]);
}
- (void)threadDemo2 {
// 1
NSLog(@"%@", [NSThread currentThread]);
// detach -> "分离"
// 直接新建线程,并且执行 @selector 方法
[NSThread detachNewThreadSelector:@selector(longOperation:) toTarget:self withObject:@"DETACH"];
// 1/2
NSLog(@"after %@", [NSThread currentThread]);
}
- (void)threadDemo1 {
NSLog(@"before %@", [NSThread currentThread]);
// 实例化一个 NSThread 对象
NSThread *t1 = [[NSThread alloc] initWithTarget:self selector:@selector(longOperation:) object:@"NSThread"];
// 启动线程
[t1 start];
// 1/2
NSLog(@"after %@", [NSThread currentThread]);
}
// 耗时操作
- (void)longOperation:(id)obj {
for (int i = 0; i < 10; ++i) {
NSLog(@"%@ %d -- %@", [NSThread currentThread], i, obj);
}
}
—— —— —— —— —— —— ——
// 如果满足某一个条件,可以让线程进入"阻塞"状态
// 休眠 - 让当前线程休眠
NSLog(@"睡会");
// 从现在开始睡几秒
[NSThread sleepForTimeInterval:1.0];
NSLog(@"再睡会");
// 睡到指定的日期 - 从现在开始间隔 2 秒
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
// 死亡 - 满足某一个条件后,退出当前所在线程
// 一旦退出了当前线程,后续的所有代码都不会执行!
[NSThread exit];