一、nsthread的初始化
1.动态方法
- (id)initwithtarget:(id)target selector:(sel)selector object:(id)argument;
// 初始化线程
nsthread *thread = [[nsthread alloc] initwithtarget:self selector:@selector(run) object:nil];
// 设置线程的优先级(0.0 - 1.0,1.0最高级)
thread.threadpriority = 1;
// 开启线程
[thread start];
参数解析:
selector :线程执行的方法,这个selector最多只能接收一个参数
target :selector消息发送的对象
argument : 传给selector的唯一参数,也可以是nil
2.静态方法
+ (void)detachnewthreadselector:(sel)selector totarget:(id)target withobject:(id)argument;
[nsthread detachnewthreadselector:@selector(run) totarget:self withobject:nil];
// 调用完毕后,会马上创建并开启新线程
3.隐式创建线程的方法
[self performselectorinbackground:@selector(run) withobject:nil];
二、获取当前线程
nsthread *current = [nsthread currentthread];
三、获取主线程
nsthread *main = [nsthread mainthread];
四、暂停当前线程
// 暂停2s
[nsthread sleepfortimeinterval:2];
// 或者
nsdate *date = [nsdate datewithtimeinterval:2 sincedate:[nsdate date]];
[nsthread sleepuntildate:date];
五、线程间的通信
1.在指定线程上执行操作
[self performselector:@selector(run) onthread:thread withobject:nil waituntildone:yes];
2.在主线程上执行操作
[self performselectoronmainthread:@selector(run) withobject:nil waituntildone:yes];
3.在当前线程执行操作
[self performselector:@selector(run) withobject:nil];
六、优缺点
1.优点:nsthread比其他两种多线程方案较轻量级,更直观地控制线程对象
2.缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销
七、下载图片的例子:
新建singeview app
新建项目,并在xib文件上放置一个imageview控件。按住control键拖到viewcontroll
er.h文件中创建imageview iboutlet
viewcontroller.m中实现:
//
// viewcontroller.m
// nsthreaddemo
//
// created by rongfzh on 12-9-23.
// copyright (c) 2012年 rongfzh. all rights reserved.
//
#import "viewcontroller.h"
#define kurl @"http://avatar.csdn.net/2/c/d/1_totogo2010.jpg"
@interface viewcontroller ()
@end
@implementation viewcontroller
-(void)downloadimage:(nsstring *) url{
nsdata *data = [[nsdata alloc] initwithcontentsofurl:[nsurl urlwithstring:url]];
uiimage *image = [[uiimage alloc]initwithdata:data];
if(image == nil){
}else{
[self performselectoronmainthread:@selector(updateui:) withobject:image waituntildone:yes];
}
}
-(void)updateui:(uiimage*) image{
self.imageview.image = image;
}
- (void)viewdidload
{
[super viewdidload];
// [nsthread detachnewthreadselector:@selector(downloadimage:) totarget:self withobject:kurl];
nsthread *thread = [[nsthread alloc]initwithtarget:self selector:@selector(downloadimage:) object:kurl];
[thread start];
}
- (void)didreceivememorywarning
{
[super didreceivememorywarning];
// dispose of any resources that can be recreated.
}
@end
线程间通讯
线程下载完图片后怎么通知主线程更新界面呢?
[self performselectoronmainthread:@selector(updateui:) withobject:image waituntildone:yes];
performselectoronmainthread是nsobject的方法,除了可以更新主线程的数据外,还可以更新其他线程的比如:
用:
运行下载图片:
图片下载下来了。