#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//[NSThread currentThread] 获取当前的线程
NSLog(@"current == %@", [NSThread currentThread]);
//[NSThread mainThread] 获取主线程
NSLog(@"main == %@", [NSThread mainThread]);
//[NSThread isMainThread] 判断当前线程是否是主线程
NSLog(@"isMainThread == %d", [NSThread isMainThread]);
#pragma mark --NSObject 开辟子线程--
// 第一个参数: selector 子线程执行的代码
// 第二个参数: 表示selector传递的参数
[self performSelectorInBackground:@selector(sayHi) withObject:@"ssss"];
self.view.backgroundColor = [UIColor redColor];
#pragma mark -- NSThread手动开辟子线程-
//使用NSThread 开辟子线程
//参数一: target
//参数二: action
//参数三: 传参
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(sayHi) object:nil];
//让线程开始执行
[thread start];
//取消线程 不会真正的取消掉线程, 而是标记 这个被取消了
[thread cancel];
#pragma mark -- 使用NSThread自动的去开辟一个线程--
//使用NSThread自动的开辟一个线程
//不需要手动开启线程
[NSThread detachNewThreadSelector:@selector(sayHi) toTarget:self withObject:nil];
}
- (void)sayHi
{
// //当前线程
// NSLog(@"current == %@", [NSThread currentThread]);
//
//
// //主线程
// NSLog(@"main == %@", [NSThread mainThread]);
int a = 10000;
for (int i = 0; i < a; i ++) {
NSLog( @"i == %d", i);
//关闭线程
//写在哪里 哪个线程就关闭了, 注意不要随意使用, 使用的时候一定要注意当前线程是否是主线程
if (i == 500) {
[NSThread exit];
}
}
//NSObject 中回到主线程去做某些事情
//参数一: 回到主线程做的事情
//参数二: 传递的参数
//参数三: 直到当前线程已经结束才去做
[self performSelectorOnMainThread:@selector(onMainThread) withObject:nil waitUntilDone:YES];
}
- (void)onMainThread
{
self.view.backgroundColor = [UIColor orangeColor];
NSLog(@"main == %@", [NSThread mainThread]);
NSLog(@"current == %@", [NSThread currentThread]);
NSLog(@"ismainThread == %d", [NSThread isMainThread]);
}