iphone ios 多线程 multi thread编程汇总



1)Threading Programming Guide

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW7

2)Concurrency(并发) Programming Guide

http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/ConcurrencyandApplicationDesign/ConcurrencyandApplicationDesign.html#//apple_ref/doc/uid/TP40008091-CH100-SW6


这两个有区别,如果各位e文好,又有耐心,就滤过下面的。

推荐

1)[Cocoa]深入浅出 Cocoa 之多线程 NSThread

http://blog.csdn.net/kesalin/article/details/6698146

2)利用iphone的多线程实现“售票系统”(手把手教你iphone开发 - 基础篇)

http://blog.csdn.net/dongfengsun/article/details/4794010

3)Concurrency 学习 (Mac & iphone) (一)

http://hi.baidu.com/songxiaoweiss/blog/item/699971d7c6c579de50da4b51.html

4)Concurrency 学习 (Mac & iphone) (二)

http://hi.baidu.com/songxiaoweiss/blog/item/82b08d13912cb4dca6ef3f29.html


找了很多网上关于ios多线程编码的文章,基本都是说到3个方法

1)detachNewThreadSelector或performSelectorInBackground

[html]  view plain copy
  1. <span style="font-size:16px;">// NSThread中的方法,启动线程Detaches a new thread and uses the specified selector as the thread entry point.  
  2. + (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument  
  3. // NSObject中的方法,启动线程Invokes a method of the receiver on a new background thread.  
  4. - (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg  
  5. // NSObject中的方法,因为更新UI只能是主线程中执行。所以这个函数主要用于子线程调用主线程中的aSelector,来更新主线程的UI或参数。  
  6. - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait</span>  

很经典的例子,主线程要更新列表图像,需要连接网络下载:

[1]主线程调用

[html]  view plain copy
  1. <span style="font-size:16px;">    [NSThread detachNewThreadSelector:@selector(downloadimg:) toTarget:self withObject:url];</span>  

[2]线程下载完毕后,通知主线程,并更新列表图像。

[html]  view plain copy
  1. <span style="font-size:16px;">        [self performSelectorOnMainThread:@selector(stateIsLoading) withObject:nil waitUntilDone:NO];</span>  

2)常规军,NSThread

[html]  view plain copy
  1. <span style="font-size:16px;">- (id)init; // designated initializer  
  2. - (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;</span>  

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

[html]  view plain copy
  1. <span style="font-size:16px;">//  SellTicketsAppDelegate.h  
  2. import <UIKit/UIKit.h>  
  3.    
  4. @interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> {  
  5.      int tickets;  
  6.      int count;  
  7.      NSThread* ticketsThreadone;  
  8.      NSThread* ticketsThreadtwo;  
  9.      NSCondition* ticketsCondition;  
  10.      UIWindow *window;  
  11.  }  
  12. @property (nonatomic, retain) IBOutlet UIWindow *window;  
  13. @end  
  14. </span>  

实现文件

[html]  view plain copy
  1. <span style="font-size:16px;">//  SellTicketsAppDelegate.m  
  2. import "SellTicketsAppDelegate.h"  
  3.    
  4. @implementation SellTicketsAppDelegate  
  5. @synthesize window;  
  6.    
  7. - (void)applicationDidFinishLaunching:(UIApplication *)application {  
  8.      tickets = 100;  
  9.      count = 0;  
  10.      // 锁对象  
  11.      ticketCondition = [[NSCondition alloc] init];  
  12.      ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  
  13.      [ticketsThreadone setName:@"Thread-1"];  
  14.      [ticketsThreadone start];    
  15.    
  16.    
  17.      ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];  
  18.      [ticketsThreadtwo setName:@"Thread-2"];  
  19.      [ticketsThreadtwo start];  
  20.      //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];  
  21.       // Override point for customization after application launch  
  22.      [window makeKeyAndVisible];   
  23.    
  24.  }  
  25.    
  26. - (void)run{  
  27.      while (TRUE) {  
  28.         // 上锁  
  29.          [ticketsCondition lock];  
  30.          if(tickets > 0){  
  31.              [NSThread sleepForTimeInterval:0.5];  
  32.              count = 100 - tickets;  
  33.              NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);  
  34.              tickets--;  
  35.          }else{  
  36.              break;  
  37.          }  
  38.          [ticketsCondition unlock];  
  39.      }  
  40.  }  
  41.    
  42. - (void)dealloc {  
  43.      [ticketsThreadone release];  
  44.      [ticketsThreadtwo release];  
  45.      [ticketsCondition release];   
  46.      [window release];  
  47.      [super dealloc];  
  48. }  
  49. @end</span>  

注意,线程initWithTarget初始化完毕后,要调用start来启动他。


“这两种方式的区别是:前一种一调用就会立即创建一个线程来做事情;而后一种虽然你 alloc 了也 init了,但是要直到我们手动调用 start 启动线程时才会真正去创建线程。这种延迟实现思想在很多跟资源相关的地方都有用到。后一种方式我们还可以在启动线程之前,对线程进行配置,比如设置 stack 大小,线程优先级。”


3)线程队列NSOperationQueue

可以参考文章使用NSOperationQueue简化多线程开发

http://marshal.easymorse.com/archives/4519


多线程在各种编程语言中都是难点,很多语言中实现起来很麻烦,objective-c虽然源于c,但其多线程编程却相当简单,可以与java相媲美。这篇文章主要从线程创建与启动、线程的同步与锁、线程的交互、线程池等等四个方面简单的讲解一下iphone中的多线程编程。

一、线程创建与启动

线程创建主要有二种方式:

- (id)init; // designated initializer
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;

当然,还有一种比较特殊,就是使用所谓的convenient method,这个方法可以直接生成一个线程并启动它,而且无需为线程的清理负责。这个方法的接口是:

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

前两种方法创建后,需要手机启动,启动的方法是:

- (void)start;

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

// SellTicketsAppDelegate.h
import <UIKit/UIKit.h>
 
@interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> {
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];
}
@end

三、线程的交互
线程在运行过程中,可能需要与其它线程进行通信,如在主线程中修改界面等等,可以使用如下接口:

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait

由于在本过程中,可能需要释放一些资源,则需要使用NSAutoreleasePool来进行管理,如:

- (void)startTheBackgroundJob {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// to do something in your thread job
...
[self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];
[pool release];
}

 

 

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才能让线程真正运行起来.

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

二 线程同步操作

IPHONE 使用NSCondition来进行线程同步,它是IPHONE的锁对象,用来保护当前访问的资源.

大致使用方法 
NSCondition* mYLock = [[NSCondition alloc] init];

[mYLock lock]

资源....

[mYLock unLock];

[mYLock release];

三 线程的交互
 
使用线程对象的
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
进行交互操作
主要是调用 主线程中指定的方法来执行一些相关操作

四 线程池 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.
}

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

NSOperationQueue *operationQueue; 
        operationQueue = [[NSOperationQueue alloc] init]; //初始化操作队列
        [operationQueue setMaxConcurrentOperationCount:n]; // 可以设置队列的个数
        [operationQueue addOperation:otherOper];

线程创建与撤销遵循 OC的内存管理规则.


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值