IOS多线程之——NSThread

来源:互联网 发布:喜马拉雅fm连不上网络 编辑:程序博客网 时间:2024/05/29 16:30

NSThread的使用

NSThread 有两种直接创建方式:

- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument

+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument

第一个是实例方法,第二个是类方法

1、[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];  2、NSThread* myThread = [[NSThread alloc] initWithTarget:self                                          selector:@selector(doSomething:)                                          object:nil];  [myThread start]; 


参数的意义:

selector :线程执行的方法,这个selector只能有一个参数,而且不能有返回值。

target  :selector消息发送的对象

argument:传输给target的唯一参数,也可以是nil

第一种方式会直接创建线程并且开始运行线程,第二种方式是先创建线程对象,然后再运行线程操作,在运行线程操作前可以设置线程的优先级等线程信息



不显式创建线程的方法:

用NSObject的类方法  performSelectorInBackground:withObject: 创建一个线程:
[Obj performSelectorInBackground:@selector(doSomething) withObject:nil];


下载图片的例子:

初始化图片链接:
#define kURL @"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg" 

初始化UIImageView:
 self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];    [self.imageView setBackgroundColor:[UIColor redColor]];    [self.view addSubview:self.imageView];        [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:kURL];

更新ui:
-(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;}

线程下载完图片后怎么通知主线程更新界面呢?

[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];

performSelectorOnMainThread是NSObject的方法,除了可以更新主线程的数据外,还可以更新其他线程的比如:

用:performSelector:onThread:withObject:waitUntilDone: 


线程同步


我们演示一个经典的卖票的例子来讲NSThread的线程同步:
.h文件:
@interface AppDelegate : UIResponder <UIApplicationDelegate>{    int tickets;    int count;    NSThread* ticketsThreadone;    NSThread* ticketsThreadtwo;    NSCondition* ticketsCondition;    NSLock *theLock;}

.m文件:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    // Override point for customization after application launch.        tickets = 100;    count = 0;    theLock = [[NSLock alloc] init];    // 锁对象    ticketsCondition = [[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];                    self.rootViewController = [[RootViewController alloc]init];    [self.window setRootViewController:self.rootViewController];    [self.window addSubview:self.rootViewController.view];                self.window.backgroundColor = [UIColor whiteColor];    [self.window makeKeyAndVisible];    return YES;}

- (void)run{    while (TRUE)    {        // 上锁        //        [ticketsCondition lock];        [theLock lock];        if(tickets >= 0){            [NSThread sleepForTimeInterval:0.09];            count = 100 - tickets;            NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);            tickets--;        }else{            break;        }        [theLock unlock];        //        [ticketsCondition unlock];    }  }

其他同步

我们可以使用指令 @synchronized 来简化 NSLock的使用,这样我们就不必显示编写创建NSLock,加锁并解锁相关代码。
- (void)doSomeThing:(id)anObj
{
    @synchronized(anObj)
    {
        // Everything between the braces is protected by the @synchronized directive.
    }
}
还有其他的一些锁对象,比如:循环锁NSRecursiveLock,条件锁NSConditionLock,分布式锁NSDistributedLock等等,可以自己看官方文档学习



著作权声明:本文由http://blog.csdn.net/totogo2010/原创,欢迎转载分享。请尊重作者劳动,转载时保留该声明和作者博客链接,谢谢!


0 0
原创粉丝点击