多线程

来源:互联网 发布:pw域名批量查询 编辑:程序博客网 时间:2024/05/16 14:52

一、如果要做比较耗时的操作的时候,就需要用到多线程。

=========================NSObject方法=============================

1.NSObject给我们提供了两个方法:

[self performSelectorInBackground:@selector(big)withObject:nil];//给选择器一个方法,让这个方法在后台执行,不影响UI界面。

  [self performSelectorOnMainThread:@selector(loadImageView:)withObject:image waitUntilDone:YES];//给选择器一个方法和参数,让这个方法在主线程中执行。

========================NSThread方法========================

2.NSThread给我们提供了两个方法

    //类方法

   [NSThreaddetachNewThreadSelector:@selector(big)toTarget:selfwithObject:nil];

    //构造方法

   NSThread *thread = [[NSThreadalloc] initWithTarget:selfselector:@selector(big)object:nil];

    [thread start];

===========================NSOperation方法========================

3.NSOperation提供了两个方法

1)NSInvocationOperation方法

1>创建一个全局队列

NSOperationQueue *_queue;

2>viewdidload方法中实例化这个队列

_queue = [[NSOperationQueuealloc] init];

3>实例化这个NSInvocationOperation

NSInvocationOperation *op1 = [[NSInvocationOperationalloc] initWithTarget:selfselector:@selector(opAction)object:nil];

4>operation添加到队列

[_queueaddOperation:op1];

2)NSOperationBlock方法

只需调用队列的这个方法即可

  [_queueaddOperationWithBlock:^{}];

3)在多线程中,有时候需要确定任务的执行顺序,肯定要建立依赖关系:

       NSBlockOperation *op1 = [NSBlockOperationblockOperationWithBlock:^{

        NSLog(@"下载%@",[NSThreadcurrentThread]);

    }];

    NSBlockOperation *op2 = [NSBlockOperationblockOperationWithBlock:^{

        NSLog(@"滤镜%@",[NSThreadcurrentThread]);

    }];

    NSBlockOperation *op3 = [NSBlockOperationblockOperationWithBlock:^{

        NSLog(@"更新%@",[NSThreadcurrentThread]);

    }];

    //建立依赖关系

    [op2 addDependency:op1];

    [op3 addDependency:op2];

   //将operation添加到队列 

    [_queueaddOperation:op1];

    [_queueaddOperation:op2];

    [_queueaddOperation:op3];

依赖关系可以跨队列执行。在指定依赖时,不能循环依赖,否则不工作。

4)控制并发的线程数量

[_queuesetMaxConcurrentOperationCount:2];

===========================GCD=============================

GCD3种不同的队列:1>全局队列   dispatch_get_global_queue

2>主队列    dispatch_get_main_queue()

3>串行队列dispatch_queue_t queue = dispatch_queue_create("myQueue",DISPATCH_QUEUE_SERIAL);

1创建队列

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

2.将任务异步执行

    dispatch_async(queue, ^{

        NSLog(@"%@",[NSThreadcurrentThread]);

    });

    dispatch_async(queue, ^{

        NSLog(@"%@",[NSThreadcurrentThread]);

    });

3.将任务添加到主队列

    dispatch_async(dispatch_get_main_queue(), ^{

        NSLog(@"%@",[NSThreadcurrentThread]);

    });

0 0