WEB开发网
开发学院手机开发iPhone 开发 iPhone 多线程 阅读

iPhone 多线程

 2010-07-06 05:10:00 来源:WEB开发网   
核心提示:tickets = 100;count = 0;// 锁对象ticketCondition = [[NSCondition alloc] init];ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) obje

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

三、线程的交互

线程在运行过程中,可能需要与其它线程进行通信,如在主线程中修改界面等等,可以使用如下接口:

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait

由于在本过程中,可能需要释放一些资源,则需要使用NSAutoreleasePool来进行管理,如:

- (void)startTheBackgroundJob {

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// to do something in your thread job

...

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

[pool release];

}

上一页  1 2 

Tags:iPhone 线程

编辑录入:coldstar [复制链接] [打 印]
赞助商链接