iPhone 多线程
多线程在各种编程语言中都是难点,很多语言中实现起来很麻烦,objective-c虽然源于c,但其多线程编程却相当简单,可以与java相媲美。这篇文章主要从线程创建与启动、线程的同步与锁、线程的交互、线程池等等四个方面简单的讲解一下iphone中的多线程编程。
一、线程创建与启动
当然,还有一种比较特殊,就是使用所谓的convenientmethod,这个方法可以直接生成一个线程并启动它,而且无需为线程的清理负责。
前两种方法创建后,需要手机启动,启动的方法是:
- (void)start;
二、线程的同步与锁
要说明线程的同步与锁,最好的例子可能就是多个窗口同时售票的售票系统了。
这是来源于网上的一个例子:
SellTicketsAppDelegate.h 文件
// SellTicketsAppDelegate.h
@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)applicationDidFinishLaun
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:selfselector:@selector(run) object:nil];
[ticketsThreadtwo setName:@"Thread-2"];
[ticketsThreadtwo start];
//[NSThread detachNewThreadSelector:@selector(run)toTarget:self withObject:nil];
// Override point for customization after applicationlaunch
[window makeKeyAndVisible];
}
- (void)run{
while (TRUE) {
// 上锁
[ticketsCondition lock];
if(tickets > 0){
}else{
}
}
}
- (void)dealloc {
}
@end
三、线程的交互
线程在运行过程中,可能需要与其它线程进行通信,如在主线程中修改界面等等,可以使用如下接口:
- (void)performSelectorOnMainThr
由于在本过程中,可能需要释放一些资源,则需要使用NSAutoreleasePool来进行管理,如:
- (void)startTheBackgroundJob {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
// to do something in your thread job
...
[selfperformSelectorOnMainThr
[pool release];
}
稍后我将做一个更加详细的demo 给大家