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