iOS多線程初體驗

來源:互聯網
上載者:User

iOS多線程初體驗是本文要介紹的內容,iPhone中的線程應用並不是無節制的,官方給出的資料顯示iPhone OS下的主線程的堆棧大小是1M,第二個線程開始都是512KB。並且該值不能通過編譯器開關或線程API函數來更改。只有主線程有直接修改UI的能力。

一、 NSOperation和NSOperationQueue

1、一個繼承自  NSOperation的操作類,該類的實現中必須有 - (void)main方法的。

2、使用NSOperation的最簡單方法就是將其放入NSOperationQueue中。

一旦一個操作被排入佇列,該隊列就會啟動並開始處理它即調用該操作類的main方法)。一旦該操作完成隊列就會釋放它。

 
  1.  self.queue = [[NSOperationQueue alloc] init];  
  2.     ArticleParseOperation *parser = [[ArticleParseOperation alloc] initWithData:filePath delegate:self];  
  3.     [queue addOperation:parser];  
  4.     [parser release];  
  5.  [queue release]; 

3、可以給操作隊列設定最多同事啟動並執行運算元: [queue setMaxConcurrentOperationCount:2];

二、NSThread

1、線程建立與啟動

線程建立主要有二種方式:

 
  1. - (id)init; // designated initializer  
  2. - (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument; 

當然,還有一種比較特殊,就是使用所謂的convenient method,這個方法可以直接產生一個線程並啟動它,而且無需為線程的清理負責。這個方法的介面是:

 
  1. + (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument 

前兩種方法建立後,需要手機啟動,啟動的方法是:

 
  1. - (void)start; 

2、線程的同步與鎖

要說明線程的同步與鎖,最好的例子可能就是多個視窗同時售票的售票系統了。我們知道在java中,使用synchronized來同步,而iphone雖然沒有提供類似java下的synchronized關鍵字,但提供了NSCondition對象介面。查看NSCondition的介面說明可以看出,NSCondition是iphone下的鎖對象,所以我們可以使用NSCondition實現iphone中的安全執行緒。這是來源於網上的一個例子:

SellTicketsAppDelegate.h 檔案

 
  1. //  SellTicketsAppDelegate.h  
  2. import <UIKit/UIKit.h> 
  3.    
  4. @interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> {  
  5.      int tickets;  
  6.      int count;  
  7.      NSThread* ticketsThreadone;  
  8.      NSThread* ticketsThreadtwo;  
  9.      NSCondition* ticketsCondition;  
  10.      UIWindow *window;  
  11.  }  
  12. @property (nonatomic, retain) IBOutlet UIWindow *window;  
  13. @endSellTicketsAppDelegate.m 檔案  
  14.  
  15. //  SellTicketsAppDelegate.m  
  16. import "SellTicketsAppDelegate.h"  
  17.    
  18. @implementation SellTicketsAppDelegate  
  19. @synthesize window;  
  20.    
  21. - (void)applicationDidFinishLaunching:(UIApplication *)application {  
  22.      tickets = 100;  
  23.      count = 0;  
  24.      // 鎖對象  
  25.      ticketCondition = [[NSCondition alloc] init];  
  26.      ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  
  27.      [ticketsThreadone setName:@"Thread-1"];  
  28.      [ticketsThreadone start];    
  29.    
  30.    
  31.      ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  
  32.      [ticketsThreadtwo setName:@"Thread-2"];  
  33.      [ticketsThreadtwo start];  
  34.      //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];  
  35.       // Override point for customization after application launch  
  36.      [window makeKeyAndVisible];   
  37.    
  38.  }  
  39.    
  40. - (void)run{  
  41.      while (TRUE) {  
  42.       // 上鎖  
  43.          [ticketsCondition lock];  
  44.          if(tickets > 0){  
  45.              [NSThread sleepForTimeInterval:0.5];  
  46.              count = 100 - tickets;  
  47.              NSLog(@"當前票數是:%d,售出:%d,線程名:%@",tickets,count,[[NSThread currentThread] name]);  
  48.              tickets--;  
  49.          }else{  
  50.              break;  
  51.          }  
  52.          [ticketsCondition unlock];  
  53.      }  
  54.  }  
  55.    
  56. - (void)dealloc {  
  57.  [ticketsThreadone release];  
  58.      [ticketsThreadtwo release];  
  59.      [ticketsCondition release];   
  60.      [window release];  
  61.      [super dealloc];  
  62. }  
  63. @end 

三、線程的互動

線程在運行過程中,可能需要與其它線程進行通訊,如在主線程中修改介面等等,可以使用如下介面:

 
  1. - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait 

由於在本過程中,可能需要釋放一些資源,則需要使用NSAutoreleasePool來進行管理,如:

 
  1. - (void)startTheBackgroundJob {  
  2.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
  3.     // to do something in your thread job  
  4.     ...  
  5.     [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];  
  6.     [pool release];  

如果你什麼都不考慮,線上程函數內調用 autorelease 、那麼會出現下面的錯誤:

 
  1. NSAutoReleaseNoPool(): Object 0x********* of class NSConreteData autoreleased with no pool in place …. 

四、關於線程池,大家可以查看NSOperation的相關資料。

小結:iOS多線程初體驗的內容介紹完了,希望本文對你有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.