1.线程的注意点
1.不要同时开太多的线程(1~3条线程即可,不要超过5条)
2.线程的概念
- 主线程: UI线程,显示、刷新UI界面,处理UI控件的事件
- 子线程: 后台线程,异步线程
3.不要把耗时的操作放在线程中,要放在子线程中执行
一:NSThread
1.创建和启动线程的3中方式
- 先创建,后启动
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];
二:常见方法
- 获取当前的线程 +(NSThread *)currentThread;
- 获取主线程 +(NSThread *)mainThread;
- 睡眠(暂停)线程
+(void)sleepUntilDate: (NSDate *)date;
+(void)sleepForTimerInterval: (NSTimeInterval)ti;
三:线程之间的通信
[self performSelectorOnMainThread:@selector(downloadFinished:) withObject:image waitUntilDone:NO]; // [self performSelector:@selector(downloadFinished:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES]; // [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
四:线程同步
1.实质:为了防止多个线程抢夺同一个资源造成的数据安全问题
2.实现:给代码加一个互斥锁(同步锁)
@synchronized(self) {
// 被锁住的代码
}
浙公网安备 33010602011771号