- (void)viewDidLoad {
[superview DidLoad];
UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 40)];
[button1 setTitle:@"数字输出"forState:UIControlStateNormal];
button1.backgroundColor= [UIColor blueColor];
button1.layer.cornerRadius= 15;
[button1 addTarget:self action:@selector(numberOut) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button1];
UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(100, 200, 100, 40)];
button2.layer.cornerRadius= 15;
[button2 setTitle:@"改变颜色" forState:UIControlStateNormal];
button2.backgroundColor= [UIColorblueColor];
[button2 addTarget:self action:@selector(changeColor) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button2];
}
- (void)numberOut {
NSLog(@"输出数字");
//主线程卡死 单线程:同一时间只能做一种事情
//开辟一个发线程让数字输出方法在分线程中去执行
//创建一个线程用来执行耗时和大数据
// self :表示当前类调用这个方法
// object :参数,不需要就nil
//第一种线程创建方式:需要要手动开启
//NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(out) object:nil];
//线程开启
//[thread start];
//第二种线程创建方式:自动开启
//[NSThread detachNewThreadSelector:@selector(thread2) toTarget:self withObject:nil];
//[NSThread detachNewThreadSelector:<#(SEL)#> toTarget:<#(id)#> withObject:<#(id)#>]
//第三种线程创建方式:隐式创建免开启
[self performSelectorInBackground:@selector(thread3) withObject:nil];
//[self performSelectorInBackground:<#(SEL)#> withObject:<#(id)#>]
//线程对应要执行的方法结束后(执行完毕)线程自动消失,如果想让这个分线程一直存在,那么就要要保证这个线程对应的方法一直在执行,
}
- (void)thread3 {
NSLog(@"隐式创建免开启");
}
- (void)thread2 {
NSLog(@"第二种创建线程方式自动开启");
}
- (void)out {
//判断当前线程是否是主线程是主线程就返回YES 分线程就返回NO
BOOL isMain = [NSThread isMainThread];
NSLog(@"%d",isMain);
if(isMain ==YES) {
NSLog(@"主线程");
} else {
NSLog(@"分线程");
}
staticinti =0;
for( ; ; ) {
i ++;
if(i == 100) {
i = 0;
}
NSLog(@"%d",i);
//线程睡眠让当前线程睡眠1秒钟后再执行
[NSThread sleepForTimeInterval:1];
//分线程跳到主线程
//方法的延时
// waitUntilDone BOOL类型YES表示等待当前方法执行完才返回主线程. NO表示执行到这句时就返回到主线程
[self performSelectorOnMainThread:@selector(numberOut) withObject:nil waitUntilDone:NO];
}
- (void)changeColor {
staticinta =1;
a++;
if(a %2 == 0) {
self.view.backgroundColor= [UIColorredColor];
} else {
self.view.backgroundColor= [UIColormagentaColor];
}
NSLog(@"改变颜色");
}