线程可以实现“多任务并行处理”,当然,这里所谓的多任务并行处理其实也不是很确切的,但是这点我们不需要关心。
线程的主要作用就是在主进程里面不方便处理的数据可以用线程去处理。
比如在主进行里面需要计算1到1000W的和,可能所需要处理的时间大概在3秒钟左右,那如果在主进程里面进行计算的话,界面就会出现常见的“无响应”。那这个时候就可以使用线程来操作了。
本文转自 http://www.999dh.net/article/iphone_ios_art/38.html 转载请注明,谢谢!
ios里面使用的线程方法有好几个,今天介绍最基本的 NSTherad来实现。
本例子主要实现:两个线程同时执行一个函数,以及对共有变量的操作。这其中还需要涉及到的知识是 进行的同步等问题。
.h文件
@interface CRViewController : UIViewController
{
NSThread * theradOne;
NSThread * theradTwo;
NSCondition * condition;
UILabel * label;
int count;
int tickets;
}
-(IBAction)buttonPresssed:(id)sender;
@property(retain,nonatomic) IBOutlet UILabel * label;
.m文件
@synthesize label;
-(IBAction)buttonPresssed:(id)sender
{
tickets = 100;
count = 0;
condition = [[NSCondition alloc] init];
theradOne = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[theradOne setName:@"One"];
[theradOne start];
theradTwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[theradTwo setName:@"Two"];
[theradTwo start];
}
-(void)updateq:(NSString*)count
{
[label setText:count];
}
-(void)run
{
while(TRUE)
{
[condition lock];
if( tickets > 0 )
{
[NSThread sleepForTimeInterval:0.1];
count = 100 - tickets;
-- tickets;
NSLog(@"tickets:%d count:%d name:%@",tickets,count,[[NSThread currentThread] name] );
NSString * str = [[NSString alloc] initWithFormat:@"%d",count];
[self performSelectorOnMainThread:@selector(updateq:) withObject:str waitUntilDone:YES];
[str release];
}
else
{
break;
}
[condition unlock];
}
}
在iphone中,线程是无法直接对界面进行更新的,所以就需要用到其他的方法,在这里使用的是
performSelectorOnMainThread ,通过这个api可以对界面进行更新,具体的参数的解释可以通过文档查询。
创建NSThread 线程的方法有2个
1. 使用 [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"aaa"];
2.使用 [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; 并对其进行 start启动。
第一个方法执行后线程立即开始执行了,而第二个方法需要使用start才会执行。