多線程在各種編程語言中都是難點,很多語言中實現起來很麻煩,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的內存管理規則.