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