NSThread(OC线程库)
主线程:一个iOS程序运行后,默认会开启1条线程,称为“主线程”或“UI线程”
主线程的主要作用
显示\刷新UI界面
处理UI事件(比如点击事件、滚动事件、拖拽事件等)
主线程的使用注意:别将比较耗时的操作放到主线程中。
耗时操作会卡住主线程,严重影响UI的流畅度,给用户一种“卡”的坏体验
#import "ViewController.h"
/**
* 1.学习
2.上厕所
*/
@interface ViewController ()
{
NSLock *_lock;
}
@end
@implementation ViewController
-(IBAction)work:(id)sender
{
[self doWorking];
}
-(IBAction)wc:(id)sender
{
//[self doWC];
//[self createTHread];
[self createTHreads];
}
#pragma mark -NSThread 多个线程
-(void)createTHreads
{
//创建3个线程
for (int i = 0; i < 3; i++) {
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(doWorking) object:nil];
thread.name = @"thread";
thread.name = [NSString stringWithFormat:@"thread%d",i];
//设计优先级
thread.threadPriority = i+1;
[thread start];
NSLog(@"%@",thread);
}
}
#pragma mark -NSTHread 单个线程-
-(void)createTHread
{
//返回的是一个单例
//创建
NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(doWorking) object:nil];
thread1.name = @"thread1";
//使用 必须调用才能使用
[thread1 start];
NSLog(@"%@",thread1);
[thread1 cancel];
//方法二
//自动执行
[NSThread detachNewThreadSelector:@selector(doWorking) toTarget:self withObject:nil];
//退出
[NSThread exit];
NSLog(@"%@",[NSThread currentThread]);
}
#pragma mark -创建任务-
/**
* 学习
*/
-(void)doWorking{
int i = 0;
while (i++<10) {
//判断主线程
NSLog(@"isMainThread:%d",[NSThread isMainThread]);
NSThread *thread = [NSThread currentThread];
[NSThread sleepForTimeInterval:1.0];
NSLog(@"%@学习了%d秒",thread.name,i);
}
NSLog(@"完成学习任务,收获颇丰");
}
/**
* 上厕所任务
*/
-(void)doWC{
//创建锁
if (_lock == nil) {
_lock = [[NSLock alloc]init];
}
//上锁
[_lock lock];
int i = 0;
while (i++<10) {
NSThread *thread = [NSThread currentThread];
[NSThread sleepForTimeInterval:1.0];
NSLog(@"%@上%d秒厕所",thread.name,i);
}
[_lock unlock];
NSLog(@"完成WC");
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"current:%@",[NSThread currentThread]);
NSLog(@"isMulti %d\n\n\n",[NSThread isMultiThreaded]);
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
NSThread 和锁机制
最新推荐文章于 2020-11-18 18:33:56 发布