零、线程的注意点(掌握)
1.不要同时开太多的线程(1~3条线程即可,不要超过5条)
2.线程概念
1> 主线程 : UI线程,显示、刷新UI界面,处理UI控件的事件
2> 子线程 : 后台线程,异步线程
3.不要把耗时的操作放在主线程,要放在子线程中执行
一、NSThread(掌握)
1.创建和启动线程的3种方式
1> 先创建,后启动
// 创建
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:nil];
// 启动
[thread start];
2> 创建完自动启动
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:nil];
3> 隐式创建(自动启动)
[self performSelectorInBackground:@selector(download:) withObject:nil];
2.常见方法
1> 获得当前线程
+ (NSThread *)currentThread;
2> 获得主线程
+ (NSThread *)mainThread;
3> 睡眠(暂停)线程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
4> 设置线程的名字
- (void)setName:(NSString *)n;
- (NSString *)name;
二、线程同步(掌握)
1.实质:为了防止多个线程抢夺同一个资源造成的数据安全问题
2.实现:给代码加一个互斥锁(同步锁)
@synchronized(self) {
// 被锁住的代码
}
![这里写图片描述](https://img-blog.csdn.net/20150614160601684)
![这里写图片描述](https://img-blog.csdn.net/20150614160548615)
#import "HMViewController.h"
@interface HMViewController ()
@end
@implementation HMViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)download:(NSString *)url
{
NSLog(@"下载东西---%@---%@", url, [NSThread currentThread]);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self createThread3];
}
/**
* 创建线程的方式3
*/
- (void)createThread3
{
[self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];
}
/**
* 创建线程的方式2
*/
- (void)createThread2
{
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];
}
/**
* 创建线程的方式1
*/
- (void)createThread1
{
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://b.png"];
thread.name = @"下载线程";
[thread start];
}
@end
#import "HMViewController.h"
@interface HMViewController ()
@property (nonatomic, strong) NSThread *thread;
@end
@implementation HMViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(download) object:nil];
}
- (void)download
{
NSLog(@"-----begin");
for (int i = 0; i<100; i++) {
NSLog(@"------%d", i);
}
NSLog(@"-----end");
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download) object:nil];
[thread start];
}
@end