`
miss大为
  • 浏览: 80220 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

【无限互联】iOS开发之多线程开发

 
阅读更多

本节要点:

1.多线程的概念

2.掌握iOS中多线程的多种创建方式

 

多线程的概念

 

 每个进程是一个应用程序,都有独立的内存空间

 一个进程中的线程共享其进程中的内存和资源

 使用多线程技术,提高CPU的使用率,防止主线程堵塞。 

 多个线程可以提高应用程序在多核系统上的实时性能

 每个程序都有⼀一个主线程,程序启动时,创建主线程,调用main 函数来启动程序。

 主线程的生命周期和程序是绑定的,程序结束时,主线程停止。

 任何有可能堵塞的任务不要在主线程执行,主线程不流畅会导致 程序界面的不流畅。(:网络访问、大文件写入磁盘、

清理缓存,等等)


多线程的创建和启动

第1种方式
[plain] view plaincopy
  1. NSThread *t = [[NSThread alloc] initWithTarget:self selector:@selector(mutableThread) object:nil];  
  2. [t start];  

第2种方式
[plain] view plaincopy
  1. [NSThread detachNewThreadSelector:@selector(mutableThread) toTarget:self withObject:nil];  

第3种方式
[plain] view plaincopy
  1. [self performSelectorInBackground:@selector(mutableThread) withObject:nil];  

第4种block语法开启一个线程
[plain] view plaincopy
  1. NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init]; [threadQueue addOperationWithBlock:^(void) {  
  2.         NSThread *t = [NSThread currentThread];  
  3.         if (![t isMainThread]) {  
  4.               NSLog(@"是多线程");   
[plain] view plaincopy
  1. }  

第5种方式线程池
[plain] view plaincopy
  1. NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init]; NSInvocationOperation *op = [[NSInvocationOperation alloc]  
  2.                                  initWithTarget:self  
  3.                                selector:@selector(mutableThread) object:nil];  
  4.     [threadQueue addOperation:op];  

第6种方式GCD,适用于多核开发
[plain] view plaincopy
  1. dispatch_queue_t network_queue;      
  2.       
  3. network_queue = dispatch_queue_create("com.myapp.network", nill);     
  4.   
  5. dispatch_async(network_queue, ^{        
  6.     UIImage *cellImage = [self loadMyImageFromNetwork:image_url];        
  7.     NSLog("多线程");      
  8.             
  9. } );   
1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics