您的位置:首页 > 移动开发 > IOS开发

ios多线程

2011-09-13 14:13 267 查看
IOS4 已经支持多线程了,我的EASYWEB在打开多个网页时会卡得要命,决定把它改成多线程方式进行加载网页

IOS4的多线程,基于Objective-c 相对 C++ JAVA来说简单不少

技术要点:

一 线程创建与启动

线程类 NSThread

包含如下线程操作方法:

//返回当前线程

+ (NSThread *)currentThread;

// 通过类方法创建一个线程

+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;

// 判断是否为多线程

+ (BOOL)isMultiThreaded;

- (NSMutableDictionary *)threadDictionary;

+ (void)sleepUntilDate:(NSDate *)date;

+ (void)sleepForTimeInterval:(NSTimeInterval)ti;

// 退出线程

+ (void)exit;

// 线程属性值

+ (double)threadPriority ;

+ (BOOL)setThreadPriority:(double)p ;

// 线程函数地址

+ (NSArray *)callStackReturnAddresses;

// 设置与返回线程名称

- (void)setName:(NSString *)n;

- (NSString *)name;

// 线程堆栈

- (NSUInteger)stackSize;

- (void)setStackSize:(NSUInteger)s;

// 判断当前线程是否为主线程

- (BOOL)isMainThread;

+ (BOOL)isMainThread;

+ (NSThread *)mainThread;

// 线程对象初始化操作 (通过创建线程对象 ,需要 手工指定线程函数与各种属性)

- (id)init;

// 在线程对象初始化时创建一个线程(指定线程函数)

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

// 是否在执行

- (BOOL)isExecuting;

// 是否已经结束

- (BOOL)isFinished;

// 是否取消的

- (BOOL)isCancelled;

// 取消操作

- (void)cancel;

// 线程启动

- (void)start;

- (void)main; // thread body method

推荐方式

// 通过类方法创建一个线程

+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;

// 在线程对象初始化时创建一个线程(指定线程函数)

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

主要通过selector:(SEL)selector 指定个功能函数,系统使其与主线程分开运行,以达到多线程的效果.

以上方式创建线程,非类方法创建需要调用 start才能让线程真正运行起来.

当多个线程同时运行,就会出现访问资源的同步问题

二 线程同步操作

要说明线程的同步与锁,最好的例子可能就是多个窗口同时售票的售票系统了。我们知道在java中,使用synchronized来同步,而iphone虽然没有提供类似java下的synchronized关键字,但提供了NSCondition对象接口。查看NSCondition的接口说明可以看出,NSCondition是iphone下的锁对象,所以我们可以使用NSCondition实现iphone中的线程安全。这是来源于网上的一个例子:

  SellTicketsAppDelegate.h 文件

  // SellTicketsAppDelegate.h

  import

  @interface SellTicketsAppDelegate : NSObject {

  int tickets;

  int count;

  NSThread* ticketsThreadone;

  NSThread* ticketsThreadtwo;

  NSCondition* ticketsCondition;

  UIWindow *window;

  }

  @property (nonatomic, retain) IBOutlet UIWindow *window;

  @end

  SellTicketsAppDelegate.m 文件

  // SellTicketsAppDelegate.m

  import "SellTicketsAppDelegate.h"

  @implementation SellTicketsAppDelegate

  @synthesize window;

  - (void)applicationDidFinishLaunching:(UIApplication *)application {

〖黑软手机资讯频道〗

  

  tickets = 100;

  count = 0;

  // 锁对象

  ticketCondition = [[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];

  //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];

  // Override point for customization after application launch

  [window makeKeyAndVisible];

  }

  - (void)run{

  while (TRUE) {

  // 上锁

  [ticketsCondition lock];

  if(tickets > 0){

  [NSThread sleepForTimeInterval:0.5];

  count = 100 - tickets;

  NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);

  tickets--;

  }else{

  break;

  }

  [ticketsCondition unlock];

  }

  }

  - (void)dealloc {

  [ticketsThreadone release];

  [ticketsThreadtwo release];

  [ticketsCondition release];

  [window release];

  [super dealloc];

  }

四 线程池 NSOperation

NSInvocationOperation是 NSOperation的子类 具体使用代码

// 建立一个操作对象

NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(myTaskMethod:) object:data];

// 将操作对象 加到系统已经的操作对列里, 这时候 myTaskMethod以一个线程的方式与主线程分开执行.

[[MyAppDelegate sharedOperationQueue] addOperation:theOp];

// 这个是真正运行在另外一个线程的“方法”

- (void)myTaskMethod:(id)data

{

// Perform the task.

}

main函数中其实只需要写你要在另外一个进程里面作的事情。比如对于我来说,我常常只是作一个简单的事情,那我会用NSInvocationOperation,NSOperation的简化版。比如说:

NSInvocationOperation *aOpt = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomeThing) object:nil];   - (void)doSomeThing { //读取大量大延迟数据等等 //可以使用performSelectorOnMainThread来将得来的数据返回到主线程 }


在doSomeThing函数里面,我可以从网上读取一些东西,但是读取是需要占用时间,而堵塞主线程的。而使用NSOperation这样使用就不会了。

而如果是NSOperation,虽然复杂了一些,又是做一个NSOperation的子类。其实main函数做得事情和doSomeThing是一抹一样的。只不过如果你制作这个子类,你对其操作的内容可以更多,可以制作更复杂的读取,载入操作等等,而且你可以重复使用这个类功能阿。再者,NSOperation也提供了对runtime操作的支持,不过那就太麻烦了,一般不大用的上。

以上是使用系统操作对列,可以使用 NSOperationQueue创建自己的线程对列

NSOperationQueue *operationQueue;

operationQueue = [[NSOperationQueue alloc] init]; //初始化操作队列

[operationQueue setMaxConcurrentOperationCount:n]; // 可以设置队列是同时被处理的“操作数

[operationQueue addOperation:otherOper];

线程创建与撤销遵循 OC的内存管理规则.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: