iphone ios 多線程 multi thread編程匯總

來源:互聯網
上載者:User

以下大家友情支援一下:

做了一個產品,需要人氣支援一下,android和iphone上91市場搜尋#super junior粉絲團#,或者直接到頁面下載http://m.ixingji.com/m.html?p=X16,大家幫忙捧捧場

老規矩,先貼2篇e文的官方文章

1)Threading Programming Guide

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW7

2)Concurrency(並發) Programming Guide

http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/ConcurrencyandApplicationDesign/ConcurrencyandApplicationDesign.html#//apple_ref/doc/uid/TP40008091-CH100-SW6


這兩個有區別,如果各位e文好,又有耐心,就濾過下面的。

推薦

1)[Cocoa]深入淺出 Cocoa 之多線程 NSThread

http://blog.csdn.net/kesalin/article/details/6698146

2)利用iphone的多線程實現“售票系統”(手把手教你iphone開發 - 基礎篇)

http://blog.csdn.net/dongfengsun/article/details/4794010

3)Concurrency 學習 (Mac & iphone) (一)

http://hi.baidu.com/songxiaoweiss/blog/item/699971d7c6c579de50da4b51.html

4)Concurrency 學習 (Mac & iphone) (二)

http://hi.baidu.com/songxiaoweiss/blog/item/82b08d13912cb4dca6ef3f29.html


找了很多網上關於ios多線程編碼的文章,基本都是說到3個方法

1)detachNewThreadSelector或performSelectorInBackground

// NSThread中的方法,啟動線程Detaches a new thread and uses the specified selector as the thread entry point.+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument// NSObject中的方法,啟動線程Invokes a method of the receiver on a new background thread.- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg// NSObject中的方法,因為更新UI只能是主線程中執行。所以這個函數主要用於子線程調用主線程中的aSelector,來更新主線程的UI或參數。- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait


很經典的例子,主線程要更新列表映像,需要串連網路下載:

[1]主線程調用

[NSThread detachNewThreadSelector:@selector(downloadimg:) toTarget:self withObject:url];

[2]線程下載完畢後,通知主線程,並更新列表映像。

        [self performSelectorOnMainThread:@selector(stateIsLoading) withObject:nil waitUntilDone:NO];


2)常規軍,NSThread

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


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

//  SellTicketsAppDelegate.himport <UIKit/UIKit.h> @interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> {     int tickets;     int count;     NSThread* ticketsThreadone;     NSThread* ticketsThreadtwo;     NSCondition* ticketsCondition;     UIWindow *window; }@property (nonatomic, retain) IBOutlet UIWindow *window;@end


實現檔案

//  SellTicketsAppDelegate.mimport "SellTicketsAppDelegate.h" @implementation SellTicketsAppDelegate@synthesize window; - (void)applicationDidFinishLaunching:(UIApplication *)application {     tickets = 100;     count = 0;     // 鎖對象     ticketCondition = [[NSCondition alloc] init];     ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];     [ticketsThreadone setName:@"Thread-1"];     [ticketsThreadone start];         ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];     [ticketsThreadtwo setName:@"Thread-2"];     [ticketsThreadtwo start];     //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];      // Override point for customization after application launch     [window makeKeyAndVisible];   } - (void)run{     while (TRUE) {     // 上鎖         [ticketsCondition lock];         if(tickets > 0){             [NSThread sleepForTimeInterval:0.5];             count = 100 - tickets;             NSLog(@"當前票數是:%d,售出:%d,線程名:%@",tickets,count,[[NSThread currentThread] name]);             tickets--;         }else{             break;         }         [ticketsCondition unlock];     } } - (void)dealloc {     [ticketsThreadone release];     [ticketsThreadtwo release];     [ticketsCondition release];      [window release];     [super dealloc];}@end


注意,線程initWithTarget初始化完畢後,要調用start來啟動他。


“這兩種方式的區別是:前一種一調用就會立即建立一個線程來做事情;而後一種雖然你 alloc 了也 init了,但是要直到我們手動調用 start 啟動線程時才會真正去建立線程。這種延遲實現思想在很多跟資源相關的地方都有用到。後一種方式我們還可以在啟動線程之前,對線程進行配置,比如設定 stack
大小,線程優先順序。”


3)線程隊列NSOperationQueue

可以參考文章使用NSOperationQueue簡化多線程開發

http://marshal.easymorse.com/archives/4519





相關文章

聯繫我們

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