图解:

从前有人说:进程是头,线程是头发!!!


关键两句话:
1.把耗时操作放在子线程。2.把修改UI的代码放在主线程。
在这里主要总结NSThread 、GCD 和 NSOperation的常用用法:
1.NSThread
创建、启动线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];
获得当前线程
NSThread *current = [NSThread currentThread];
线程的名字
- (void)setName:(NSString *)n;
- (NSString *)name;
控制线程状态:

安全隐患解决 – 互斥锁(是一种线程同步技术,即多条线程在同一条线上执行(按顺序地执行任务)
互斥锁使用格式
@synchronized(锁对象) { // 需要锁定的代码 }
注意:锁定1份代码只用1把锁,用多把锁是无效的,一般当线程抢夺同一份资源(修改同一个数据)要加锁
OC在定义属性时有nonatomic和atomic两种选择
atomic:原子属性,为setter方法加锁(默认就是atomic)
nonatomic:非原子属性,不会为setter方法加锁
线程间通信

线程间通信常用方法:
//创建子线程任务并执行
[self performSelectorInBackground:@selector(download) withObject:nil];
//回到主线程方法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
网友评论