IOS中的线程操作(2)

接上一篇

2、NSOperation

NSOperation是一个抽象类,本身并没有办法去直接使用,如果我们要使用它,就要去使用它的子类。IOS已经给我们提供了两个已经实现好的子类,NSInvocationOperation和NSBlockOperation。

对于这两个子类虽然IOS本身提供了start方法,不过我们一般不去直接使用它而需要借助另外一个类 NSOperationQueue 。

NSOperationQueue顾名思义是一个操作队列,他会给我们提供一个有序的执行队列,看一下苹果官方对这个类的描述

 The NSOperationQueue class regulates the execution of a set of NSOperation objects. After being added to a queue, an operation remains in that queue until it is explicitly canceled or finishes executing its task. Operations within the queue (but not yet executing) are themselves organized according to priority levels and inter-operation object dependencies and are executed accordingly. An application may create multiple operation queues and submit operations to any of them.

Inter-operation dependencies provide an absolute execution order for operations, even if those operations are located in different operation queues. An operation object is not considered ready to execute until all of its dependent operations have finished executing. For operations that are ready to execute, the operation queue always executes the one with the highest priority relative to the other ready operations. For details on how to set priority levels and dependencies, see NSOperation Class Reference.

You cannot directly remove an operation from a queue after it has been added. An operation remains in its queue until it reports that it is finished with its task. Finishing its task does not necessarily mean that the operation performed that task to completion. An operation can also be canceled. Canceling an operation object leaves the object in the queue but notifies the object that it should abort its task as quickly as possible. For currently executing operations, this means that the operation object’s work code must check the cancellation state, stop what it is doing, and mark itself as finished. For operations that are queued but not yet executing, the queue must still call the operation object’s start method so that it can processes the cancellation event and mark itself as finished. 

大概意思是 NSOperationQueue类调节一组的NSOperation对象的执行。在队列中的NSOperation对象会按照绝对的顺序去执行,也就是说当任务加入到任务队列后,会自动按照优先级和依赖关系自动运行。

还是上面的例子

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

//    NSThread *mThread = [[NSThread alloc] initWithTarget:self selector:@selector(DownImage:) object:IMAGE_PATH];
//    [mThread start];
    NSInvocationOperation *mOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(DownImage:) object:IMAGE_PATH];

//    [mOperation start];
    NSOperationQueue *mQueue = [[NSOperationQueue alloc] init];
    [mQueue addOperation:mOperation];
}

看上去很简单,仅仅就是创建任务,然后加入到队列。这个队列是个任务的pool,遵循生产者-消费者的关系,当有任务的时候会自动运行任务。我们可以使用setMaxConcurrentOperationCount:这个方法来设置这个queue里面的线程总数,默认值是-1,意思是没有限制。

在继承NSOperation后,对于非并发的工作,需要实现NSOperation子类的main方法:

-(void)main

{

@try

{

// 处理工作任务

}

@catch(…)

{

// 处理异常,但是不能再重新抛出异常

}

}

因为NSOperation的任务是可以cancel的,所以在main方法处理任务时就要不断轮询isCancelled。另外,这个main方法本来是空的,所以不需要调用[super main]这句。

还有一个start方法,这个start方法是工作的入口,通常是用来设置线程需要的运行环境的。和main一样,不要调用[super start]。这个方法还会区分这个运行的状态,如果是canceled或者已经结束了,这个任务就不会运行;而如果是正在运行或者还没ready,则会扔出一个异常。

如果要支持并发任务,至少需要重写start、isConcurrent、isExecuting、isFinished四个方法。这里需要说一下这个isConcurrent方法,这个方法是标志operation是否并行执行的,如果是concurrent的,则返回YES;反之,则返回NO。如果没有重写这个方法,则默认NO,但在OS X10.6之后,这个值被忽略了。

另外,NSOperation的一些属性是支持KVC的,我们可以通过KVO方法来观察这些属性并在应用的其他地方来控制程序运行,所以需要在合适的时候发出KVO通知。

NSOperation支持的KVO属性有:isCancelled、isConcurrent、isExecuting、isFinished、isReady、dependencies、queuePriority、completionBlock。如果你增加了属性,推荐同样支持KVC和KVO。

时间: 2024-08-27 06:56:04

IOS中的线程操作(2)的相关文章

IOS中的线程操作(1)

IOS 上提供的多线程方法只要分为三种,1.NSThread 2.NSOperation 3.GCD ([self performSelectorInBackground:SEL withObject:id] 这个方法本质上也是一种多线程的方式),三种方式抽象程度越来越高,代码的编写难度也越来越简单. 1.NSThread: NSThread比其他两个都要更轻量级,但需要自己来管理线程的生命周期和同步,代码的编写上比其他两个复杂. NSThread提供了两种初始化方式,一种是传统的init方法

IOS中的线程操作(3)

使用CGD比前面两种更高效(据说是这样,有兴趣的同学可以去试试).这也是苹果比较推荐使用的方式. GCD是Grand Central Dispatch的缩写,是一组用于实现并发编程的C接口.GCD是基于Objective-C的Block的特性开发的,基本的业务逻辑和NSOperation很像.都是添加一个任务到一个队列,由系统来负责线程的生成和调度.因为直接使用Block,所以使用起来很是方便,降低了多线程开发的门槛. 还是前两节下载图片的例子,让我们看一下使用GCD模式该怎样做. #impor

Java与iOS中的线程安全与线程同步

Java 中的线程安全与线程同步: 创建一个 Thread的实现类 MyThread , 作为线程体; 创建 Test 类, 在主函数中生成两个 Thread 对象, 两个对象公用一个线程体( MyThread 的对象 ); 线程安全: 避免多个线程同时访问统一资源; 解决办法: 加同步锁;  synchronized(this) { 要访问的资源; } iOS 中的线程安全与线程同步 线程安全: 同一资源在统一时间只能允许一个线程进行访问 解决办法: 方法一: 加同步锁 @synchroniz

Python程序中的线程操作-锁

Python程序中的线程操作-锁 一.同步锁 1.1多个线程抢占资源的情况 from threading import Thread import os,time def work(): global n temp=n time.sleep(0.1) n=temp-1 if __name__ == '__main__': n=100 l=[] for i in range(100): p=Thread(target=work) l.append(p) p.start() for p in l:

Python程序中的线程操作-concurrent模块

Python程序中的线程操作-concurrent模块 一.Python标准模块--concurrent.futures 官方文档:https://docs.python.org/dev/library/concurrent.futures.html 二.介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 ProcessPoolExecutor:进程池,提供异步调用 两者都实现相同的接口,该接口由抽象Execut

Python程序中的线程操作(线程池)-concurrent模块

目录 Python程序中的线程操作(线程池)-concurrent模块 一.Python标准模块--concurrent.futures 二.介绍 三.基本方法 四.ProcessPoolExecutor 五.ThreadPoolExecutor 六.map的用法 七.回调函数 Python程序中的线程操作(线程池)-concurrent模块 一.Python标准模块--concurrent.futures 官方文档:https://docs.python.org/dev/library/con

iOS 中SQLite数据库操作

在iOS中实现SQLite数据库的操作:1.导入框架(libsqlite3.0.tbd) 2.导入头文件<sqlite3.h> 3.实现数据的增删改查 实现简单 SQLite数据库操作 的 demo 具体过程: 1.创建名为 SQLite_Manage 的.h .m 文件,导入头文件 <sqlite3.h> 2.数据库在一个app中只有一个,使用单例模式:(代码如下) 1 + (SQLite_Manager *)sharedManager{ 2 static SQLite_Mana

iOS中保证线程安全的几种方式与性能对比

来源:景铭巴巴 链接:http://www.jianshu.com/p/938d68ed832c 一.前言 前段时间看了几个开源项目,发现他们保持线程同步的方式各不相同,有@synchronized.NSLock.dispatch_semaphore.NSCondition.pthread_mutex.OSSpinLock.后来网上查了一下,发现他们的实现机制各不相同,性能也各不一样.不好意思,我们平常使用最多的@synchronized是性能最差的.下面我们先分别介绍每个加锁方式的使用,在使用

118 python程序中的线程操作-创建多线程

一.python线程的模块 1.1 thread和threading模块 thread模块提供了基本的线程和锁的支持 threading提供了更高级别.功能更强的线程管理的功能. 1.2 Queue模块 Queue模块允许用户创建一个可以用于多个线程之间共享数据的队列数据结构. 1.3注意模块的选择 避免使用thread模块 因为更高级别的threading模块更为先进,对线程的支持更为完善 而且使用thread模块里的属性有可能会与threading出现冲突: 其次低级别的thread模块的同