iphone中如何进行多线程编程
2010-04-26, Posted in Objective-c, 软件开发 | 15 回复

多线程在各种编程语言中都是难点,很多语言中实现起来很麻烦,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]; }
如果你什么都不考虑,在线程函数内调用 autorelease 、那么会出现下面的错误:
NSAutoReleaseNoPool(): Object 0x********* of class NSConreteData autoreleased with no pool in place ….
四、关于线程池,大家可以查看NSOperation的相关资料。
相关日志
14 Comments for this entry
1 Trackback or Pingback for this entry
-
iPhone中如何进行多线程编程 | 第三极 | 移动开发者
四月 23rd, 2011 on 12:25:44[...] 原文链接:http://www.voland.com.cn/iphone-in-the-multi-threaded-programming >>> 进入[Android2D游戏开发]主题文章列表 转载编辑: Fgamers [...]
四月 26th, 2010 on 12:15:26
呵呵,你玩的是高科技哦
四月 26th, 2010 on 13:12:18
没有那么先进吧,哈哈,开始玩iphone的编程是2年前了,那会还是用window上开发,然后通过ssh 上传到iphone真机上调试,开始一个炒股的程序,大家花了半年时间,现在好了,用黑苹果,资料也多,开发起来容易多了
四月 26th, 2010 on 15:16:40
来过,新的奋斗周开始了…
四月 27th, 2010 on 08:49:24
兄弟努力呀:)
四月 27th, 2010 on 00:48:53
地震年啊,真是不太平,台湾又大地震了….郁闷,2012要来了?
四月 27th, 2010 on 08:48:32
传说中的谣言?
四月 27th, 2010 on 12:14:35
呵呵,来支持下,嘿嘿!!
常来看看!
四月 27th, 2010 on 16:01:16
感谢!感谢:)
四月 28th, 2010 on 23:01:14
niubility~ 我倒是可以推荐做编程的朋友来看看你的blog~~哈`
四月 29th, 2010 on 08:46:17
编程也得看对不对路哦,开发的语言太多了,不过编程思路倒是通的:)
九月 13th, 2010 on 10:53:02
问下,用objective-c怎么做图片的加载啊 我刚起步学这个,好多都还不会,谢谢
十月 9th, 2010 on 13:24:42
图片的加载有很多方式,看你加载图片后做什么用,比如你在View中,想设置一下背景,直接使用如下:[self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg1.png"]]];
七月 2nd, 2011 on 08:46:54
路过~~
一月 11th, 2012 on 14:41:17
这篇文章非常不错,good!