Nsthread
(1) Basic use of Nsthread
//第一种创建线程的方式:alloc init.//特点:需要手动开启线程,可以拿到线程对象进行详细设置 //创建线程 /* 第一个参数:目标对象 第二个参数:选择器,线程启动要调用哪个方法 第三个参数:前面方法要接收的参数(最多只能接收一个参数,没有则传nil) */ NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"daquan"]; //启动线程 [thread start];//第二种创建线程的方式:分离出一条子线程//特点:自动启动线程,无法对线程进行更详细的设置 /* 第一个参数:线程启动调用的方法 第二个参数:目标对象 第三个参数:传递给调用方法的参数 */ [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"我是分离出来的子线程"];//第三种创建线程的方式:后台线程//特点:自动启动线程,无法进行更详细设置[self performSelectorInBackground:@selector(run:) withObject:@"我是后台线程"];
(2) Setting the properties of a thread
//设置线程的属性 //设置线程的名称 thread.name = @"线程A"; //设置线程的优先级,注意线程优先级的取值范围为0.0~1.0之间,1.0表示线程的优先级最高,如果不设置该值,那么理想状态下默认为0.5 thread.threadPriority = 1.0;
(3) Status of the thread
//线程的各种状态:新建-就绪-运行-阻塞-死亡//常用的控制线程状态的方法[NSThread exit];//退出当前线程[NSThread sleepForTimeInterval:2.0];//阻塞线程[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];//阻塞线程//注意:线程死了不能复生,即不能再使用该线程.
(4) Thread safety
01 前提:多个线程访问同一块资源会发生数据安全问题
02 解决方案:加互斥锁
03 相关代码:@synchronized(锁对象){//需要锁定的代码}
04 专业术语-线程同步 05 原子和非原子属性(是否对setter方法加锁)
(5) Inter-thread communication
-(void) Touchesbegan: (nonnull nsset<uitouch *> *) touches withevent: (Nullable uievent *) event{//[self download2]; Open a thread to download the picture [Nsthread detachnewthreadselector: @selector (downloadimage) totarget:self Withobject:nil];} -(void) downloadimage{//1. Determines the URL of the network image to download, a URL uniquely corresponds to a resource on the network nsurl *url = [Nsurl urlwithstring:@] Http://p6.qhimg.com /t01d2954e2799c461ab.jpg "]; 2. Download the image data to local (binary data) according to the URL address nsdata *data = [NSData Datawithcontentsofurl:url]; 3. Convert the binary data downloaded to the local image UIImage *image = [UIImage imagewithdata:data]; 4. Back to the main thread refresh UI//4.1 first way//[self Performselectoronmainthread: @selector (showImage:) withobject:image waituntildone:y ES]; 4.2 The second way (call the system directlysetImage:method)//[Self.imageviw Performselectoronmainthread: @selector (setimage:) withobject:image Waituntildone:yes]; 4.3 Third Way (can select any thread) [Self.imageview performselector: @selector (setimage:) onthread:[nsthread Mainthread] Withobject : Image Waituntildone:yes];}
(6) How to calculate the execution time of a code snippet
//第一种方法 NSDate *start = [NSDate date]; //2.根据url地址下载图片数据到本地(二进制数据) NSData *data = [NSData dataWithContentsOfURL:url]; NSDate *end = [NSDate date]; NSLog(@"第二步操作花费的时间为%f",[end timeIntervalSinceDate:start]);//第二种方法 CFTimeInterval start = CFAbsoluteTimeGetCurrent(); NSData *data = [NSData dataWithContentsOfURL:url]; CFTimeInterval end = CFAbsoluteTimeGetCurrent(); NSLog(@"第二步操作花费的时间为%f",end - start);
Create threading Mode-nsthread