iOS中实现多线程的几种方案
- 1.pThread
- 2.NSThread
- 3.GCD
- 4.NSOperation
pThread
- C语言实现,一套通用的API,具有跨平台性,但是使用难度较大,生命周期由程序员管理。
NSThread
- 创建线程的三种方式:
/*
第一个参数:目标对象 self
第二个参数:方法选择器 线程创建之后要执行的任务
第三个参数:传递给run:方法的参数
*/
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"创建线程的第一种方法"];
[thread start];
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分离出一条子线程"];
[self performSelectorInBackground:@selector(run:) withObject:@"创建一条后台线程"];
- 可以通过一个属性来设置线程的优先级
//设置线程的优先级 0.0 ~ 1.0 取值范围 最高是1.0 如果不设置那么默认是0.5
threadA.threadPriority = 1.0;
线程安全问题
- 很多时候,当多个线程同时访问同一块资源的时候,需要加一个同步锁
//给代码加一把同步锁
//token 锁对象:全局唯一对象
//注意点:1)加锁需要耗费性能
// 2)注意加锁的位置
// 3)注意加锁的条件:多线程访问同一块资源的时候
@synchronized (self) {
}
NSThread线程间的通信问题
[self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:NO];
[self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
如果单纯的是给imageView设置图片,我们可以借用系统的setImage方法,
[self.imageView performSelectorOnMainThred:@selector(setImage:) withObject:image waitUntilDone:YES];
网友评论