iOS中使用多线程的原因:
1,iOS中只有主线程有直接修改Ui的权利
2,iPhone中主线程堆栈1M,新开辟的线程堆栈512K
3,多任务,多核,效率,用户体验共同决定
(一)GCD(Grand Central dispatch)block和dispatch,可以简化多核多线程编程,iOS4以后支持
1,block的定义类似于函数指针;block对象(块对象);
可以存在block数组;
但block存储在函数栈中,注意大括号中的生命周期;
2,block典型用法,图片下载应用中的块应用,嵌套异步block块的使用,如果前面ok,则去UI更新
dispatch_async(dispatch_queue_create("com.enormego.EGOImageLoader",NULL), ^{
UIImage* image = styler(anImage);
[[EGOCache currentCache] setImage:image forKey:keyForURL(aURL, style) withTimeoutInterval:604800];
dispatch_async(dispatch_get_main_queue(), ^{
completion(image, aURL, nil);
});
});
(二)NSOperation和NSOpertionQueue
1,一个继承自NSOperation的操作类,该类的实现中必须有 (void) main()方法
2,最简单的方法,将NSOperation的实例放入NSOpertionQueue中
3,可以在NSOpertionQueue中设置同时可以进行的操作数
(三)NSThread
1,detachNewThreadSelector此为简便方法,不用进行线程清理
[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];
2,NSThread initialWithTarget, (void)start;方法,可以创建线程,但选择合适的时机启动线程
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(myThreadMainMethod:)
object:nil];
[myThread start];
(四)线程间同步
1,原子锁属性,automic,noautomic,变量可以保证多线程访问
2,NSCondition,可以提供带条件的同步锁,解锁时,需要输入相同的条件才能解锁
3,NSLock, lock,unlock比较简单的同步锁
4,@synchronized(anObject)更简单的所方式,通常用在单例对象的创建上面
原文:http://blog.csdn.net/hongwu32/article/details/20555081