iPhone 多线程
2010-07-06 05:10:00 来源:WEB开发网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];
}
- ››iphone图片拉伸的几种方法
- ››iphone正则表达式的简单使用
- ››iPhone开发Unresolved Symbols CAKeyframeAnimati...
- ››IPhone开发-“此证书是由未知颁发机构签名”解决方...
- ››IPhone开发-整合私钥和证书,生成.p12文件
- ››iPhone应用开发-UIPickerView选取器详解
- ››iphone 获取屏幕的宽度和高度
- ››iPhone读取工程包中的二进制文件
- ››iPhone新手机 不挂YouTube APP
- ››iPhone 获取指定格式的时间和日期
- ››iPhone版PPS走进生活 观赏体验媲美PC版
- ››iPhone两种不同的应用程序:两种方法的哲学思想
更多精彩
赞助商链接