NSThread 的创建和使用
1) 实例化创建,需要主动开启线程
//创建线程,需要手动启动
/*
* selector:自定义方法
* object:给函数传递的参数(例如:下载方法中网址)
*/
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downLoad:) object:@"url"];
//启动
[thread start];
2) 自动启动的创建方法
//创建线程,自动启动
[NSThread detachNewThreadSelector:@selector(downLoad:) toTarget:self withObject:@"url"];
3) 隐式创建并启动
//其他创建方式(子线程)
[self performSelectorInBackground:@selector(downLoad:) withObject:@"other"];
//其他创建方式(主线程)
[self performSelectorOnMainThread:@selector(downLoad:) withObject:@"main" waitUntilDone:YES];
相关方法:
(1) 获取主线程 [NSThread mainThread];
(2) 获取当前线程 [NSThread currentThread];
(3) 是否为主线程
@property (readonly) BOOL isMainThread
+ (BOOL)isMainThread
(4) 线程的名字
@property (nullable, copy) NSString *name
线程状态控制:
(1) 启动线程
- (void)start;
(2) 阻塞(暂停)线程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
(3)强制停止线程
+ (void)exit;
(4) 线程优先级
//线程的调度优先级:调度优先级的取值范围是0.0 ~ 1.0,默认0.5,值越大,优先级越高
+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;
实例:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blueColor];
}
- (void)download:(NSString *)url{
for (int i =0; i< 5; ++i){
NSLog(@"%@__%@", url, [NSThread currentThread]);
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"__touchesBegan_%@", [NSThread currentThread]);
//[self createThread1];
//[self createThread2];
[self createThread3];
}
//隐式创建线程,创建完成后自动启动
- (void)createThread3{
[self performSelectorInBackground:@selector(download:) withObject:@"隐式创建线程,创建完成后自动启动"];
}
//创建线程方法二,创建完成后自动启动
- (void)createThread2{
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"创建完成后自动启动"];
}
//创建线程方法一,需要自己启动
- (void)createThread1{
//[NSThread currentThread]获取当前线程
//[NSThread mainThread]获取主线程
//创建线程A
NSThread *threadA = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"threadA"];
threadA.name = @"threadA";
//启动线程
[threadA start];
//创建线程B
NSThread *threadB = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"threadB"];
threadB.name = @"threadB";
//启动线程
[threadB start];
}
@end
初始化创建方法,需要手动启动
创建完成后自动启动
隐式创建