解析iphone多線程

來源:互聯網
上載者:User

不管是iphone
中還是其他的作業系統,多線程在各種程式設計語言中都是痛點,很多語言中實現起來很麻煩,objective-c雖然源於c,但其多線程編程卻相當簡單,可以與java
相媲美。多線程編程是防止主線程堵塞,增加運行效率等等的最佳方法。而原始的多線程方法存在很多的毛病,包括線程鎖死等。

一、線程建立與啟動

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

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

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

 
  1. (void)detachNewThreadSelector:  
  2. (SEL)aSelector toTarget:  
  3. (id)aTarget withObject:  
  4. (id)anArgument 

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

 
  1. (void)start; 

二、線程的同步與鎖

要說明線程的同步與鎖,最好的例子可能就是多個視窗同時售票的售票系統了。我們知道在java中,使用synchronized來同步,而iphone

然沒有提供類似java下的synchronized關鍵字,但提供了NSCondition對象介面。查看NSCondition的介面說明可以看
出,NSCondition是iphone下的鎖對象,所以我們可以使用NSCondition實現iphone中的安全執行緒。這是來源於網上的一個例
子:

SellTicketsAppDelegate.h 檔案

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

三、線程的互動

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

 
  1. (void)performSelectorOnMainThread:  
  2. (SEL)aSelector withObject:  
  3. (id)arg waitUntilDone:  
  4. (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];  

小結:

對於多線程,在一個程式中,一些獨立啟動並執行程式片斷叫作線程,利用它編程的概念就叫作多執行緒。多執行緒一個常見的例子就是使用者介面。利用線程,使用者可按下一個按鈕,然後程式會立即作出響應,而不是讓使用者等待程式完成了當前任務以後才開始響應

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.