iOS-多线程 - 02(NSThread简单使用1)
//NSThread:基于OC
//NSThread创建,第一种 init方法->start
[self threadCreate1];
//NSThread创建,第二种 创建后直接开启
[self threadCreate2];
//NSThread创建,第三种 隐式创建, NSObjc的方法, 任何对象都可以调用
[self threadCreate3];
#pragma mark - NSThread第一种创建方式
- (void)threadCreate1 {
NSThread *threadA = [[NSThread alloc] initWithTarget:self selector:@selector(gothread1:) object:@"第一种"];
//线程的名字
threadA.name = @"线程A";
[threadA start];
NSThread *threadB = [[NSThread alloc] initWithTarget:self selector:@selector(gothread1:) object:@"第一种"];
//线程的名字
threadB.name = @"线程B";
[threadB start];//线程已开启就会执行(在子线程中)gothread:方法, 并且将@"haha"传过去
}
- (void)gothread:(NSString *)string {
//获取线程调度的优先级//取值0.0~1.0, 默认0.5, 值越大, 优先级越高
double nowY = [NSThread threadPriority];
NSLog(@"%f", nowY);
//设置某个方法执行的线程的优先级, 在方法里设置高一点即可调度的多
[NSThread setThreadPriority:0.9];
NSLog(@"%@, string = %@", [NSThread currentThread], string);
NSLog(@"%@, string = %@", current.name, string);
}
//NSThread *current = [NSThread currentThread];//获得当前的线程
//NSThread *main = [NSThread mainThread];//获取主线程
//判断当前执行的是什么线程,返回YES或NO
//1,用线程对象去调用
[current isMainThread];
//2,类方法
[NSThread isMainThread];
#pragma mark - NSThread第二种创建方式, 创建后直接启动
- (void)threadCreate2 {
[NSThread detachNewThreadSelector:@selector(gothread2:) toTarget:self withObject:@"第二种"];
}
- (void)gothread2:(NSString *)string {
NSLog(@"%@", string);
}
#pragma mark - NSThread第三种创建方式(隐式方式)
//简单快捷, 但是无法设置详细的配置
- (void)threadCreate3 {
//任何对象都可以调用,在后台线程中 === 在子线程中执行
[self performSelectorInBackground:@selector(gothread3:) withObject:@"第三种"];
}
- (void)gothread3:(NSString *)string {
NSLog(@"string = %@", string);
}