/********线程的状态**************************************/
线程的状态:新建状态(New)--->就绪状态(Runnable)----->运行状态(Running)---->阻塞状态(Blocked)---->死亡状态(Dead)
- (void)start;
// 进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态
阻塞(暂停)线程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// [NSThread sleepForTimeInterval:2]; // 让线程睡眠2秒(阻塞2秒)
// [NSThread sleepUntilDate:[NSDate distantFuture]];
// 进入阻塞状态
+ (void)exit;
// 进入死亡状态
/********多线程安全隐患的解决方法(互斥锁)**************************************/
@synchronized(锁对象) { // 需要锁定的代码 }
注意:锁定1份代码只用1把锁,用多把锁是无效的,一般用控制器对象self作为锁对象
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
线程间另一种通信方式 – 利用NSPort
NSPort;
NSMessagePort;
NSMachPort;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//开启一条子线程
[self performSelectorInBackground:@selector(download) withObject:nil];
}
// 子线程方法
- (void)download
{
// 图片的网络路径
NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];
// 加载图片
NSData *data = [NSData dataWithContentsOfURL:url];
// 生成图片
UIImage *image = [UIImage imageWithData:data];
// 回到主线程,显示图片
[self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
// [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
// [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
}
/********NSThread开启线程的三种方式方式@"jack"(线程的名字)*****/
- (void)createThread3
{
[self performSelectorInBackground:@selector(run:) withObject:@"jack"];
}
- (void)createThread2
{
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"rose"];
}
- (void)createThread1
{
// 创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"jack"];
// 启动线程
[thread start];
}