线程

- (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(@"改变颜色");

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、多线程基础 基本概念 进程进程是指在系统中正在运行的一个应用程序每个进程之间是独立的,每个进程均运行在其专用且...
    AlanGe阅读 3,567评论 0 0
  • 进程和线程 首先,在了解多线程之前要了解什么是进程,什么是线程 什么是进程呢?进程是指在系统中正在运行的一个应用程...
    搁浅的青蛙阅读 3,025评论 0 0
  • NSThread 第一种:通过NSThread的对象方法 NSThread *thread = [[NSThrea...
    攻城狮GG阅读 4,284评论 0 3
  • 今天晚上我又难过得想哭 像月球潮汐般神秘的情绪 我总弄不透它 也许是因为孤独 这个要做一辈子的功课 我有时也能考及...
    康文阅读 3,273评论 0 0
  • 这部影片,其实之前我也关注过,当时为了推广这部影片,发行人方励下跪求排片的事件引起了很多人的关注,我也是因为...
    予之舟阅读 4,097评论 2 2