Objective-C(IOS)中多線程樣本

來源:互聯網
上載者:User
// 初始化鎖對象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];- (void)run{    while (TRUE) {      // 上鎖      [ticketsCondition lock];          //dosomething..      [ticketsCondition unlock];    }}//釋放資源。- (void)dealloc {   [ticketsThreadone release];   [ticketsThreadtwo release];   [ticketsCondition release];           [super dealloc];}//線程在運行過程中,可能需要與其它線程進行通訊,如在主線程中修改介面等等,可以使用如下介面:- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait如:[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];//updateUI為和UI交換的方法名。//NSAutoreleasePool啟用。

 

使用另一種方法建立後檯子線程:

//用到的類是NSThread類,這裡使用detachNewTheadSelector:toTagaet:withObject建立一個線程。//函數setupThread:(NSArray*)userInfor。通過userInfor將需要的資料傳到線程中。//函數定義:-(void)setupThread:(NSArray*)userInfor{   [NSThread detachNewThreadSelector:@selector(threadFunc:) toTarget:self withObject:(id)userInfor];
//注意threadFunc後面帶冒號,方法threadFunc帶id參數}- (void)threadFunc:(id)userInfor{ NSAutoreleasePool*pool = [[NSAutoreleasePool alloc] init]; //。。。。需要做的處理。 //這裡線程結束後立即返回 [self performSelectorOnMainThread:@selector(endThread) withObject:nil waitUntilDone:NO]; [pool release];}//performSelectorOnMainThread通知主線程執行函數endThread。也可以使用performSelector:onThread:withObject:waitUntil 通知某線程執行線程結束後的處理。//線程內不要重新整理介面。如果需要重新整理介面,通過performSelectorOnMainThread,調出主線程中的方法去重新整理。
相關文章

聯繫我們

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