对多线程的理解,IOS中有几种实现多线程的方法

来源:互联网 发布:唐国强三国演义知乎 编辑:程序博客网 时间:2024/05/22 06:58

1、好处:

1、使用线程可以把程序中占据时间长的任务放到后台去处理,如图片、视频的下载

2、发挥多核处理器的优势,并发执行让系统运行的更快、更流畅,用户体验更好

缺点:

1、大量的线程降低代码的可读性,

2、更多的线程需要更多的内存空间

3、当多个线程对同一个资源出现争夺的时候要注意线程安全的问题。

iOS有三种多线程编程的技术:

1、NSThread(两种创建方式)

[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];

NSThread *myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:nil];

[myThread start];

2、NSOperationQueue

NSOperationQueue*oprationQueue= [[NSOperationQueuealloc] init];

oprationQueueaddOperationWithBlock:^{

//这个block语句块在子线程中执行

}

http://alloc.sinaapp.com/wp/?p=237

3、Grand Central Dispatch (GCD)

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

//耗时的操作

dispatch_async(dispatch_get_main_queue(), ^{

//更新界面

});

});

http://blog.csdn.net/totogo2010/article/details/8016129

PS:不显示的创建线程的方法:

用NSObject的类方法performSelectorInBackground:withObject:创建一个线程:[Obj performSelectorInBackground:@selector(doSomething) withObject:nil];



文/一首白城(简书作者)
原文链接:http://www.jianshu.com/p/522c37d817de
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
0 0
原创粉丝点击