Objective-C(IOS)中多線程示例


// 初始化鎖對象
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,調出主線程中的方法去刷新。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM