今天看了多線程的問題,看到多種實現多線程的方法,個人覺得多線程甚是強大,真是物盡其用啊。興趣即起,總結了5中方法如下:
第一種方法,直接開啓一個線程來運行
[self performSelectorInBackground:@selector(doSomeThing) withObject:nil];
第二種方法,直接創建一個線程,SEL參數是指這個線程需要執行的任務,使用這個方法的話,線程直接啓動,但是不能控制線程什麼時候關閉
[NSThread detachNewThreadSelector:@selector(doSomeThing) toTarget:self withObject:nil];
第三種方法,初始化一個線程並將線程啓動,否則線程不會執行的。這種創建線程的方式是可以控制線程開始和關閉的,線程本身有對應的方法cancel
NSThread *thread = [[NSThread alloc ]initWithTarget:self selector:@selector(doSomeThing) object:nil];
// 啓動線程
[thread start];
第四種方法,創建一個線程隊列,並在線程隊列中添加操作對象(兩種,詳解如下)
// 創建一個線程隊列 NSOperationQueue *operationQuene = [[NSOperationQueue alloc]init]; // 創建一個操作對象,這個操作對象定義了線程需要做的任務。 // 1、NSInvocationOperation NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(doSomeThing) object:nil]; // 將創建好的操作對象放進線程隊列中,這樣線程就可以直接啓動了。 [operationQuene addOperation:operation]; // 2、NSBlockOperation NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{ [NSThread sleepForTimeInterval:5]; NSThread *thread = [NSThread currentThread]; if ([thread isMainThread]) { NSLog(@"Main Thread"); }else{ NSLog(@"Peer Thread"); } NSLog(@"DONE"); }]; [operationQuene addOperation:blockOperation];這裏需要注意的是:不能直接用NSOperation來定義一個操作對象,因爲NSOperation只是一個抽象的類。我們若要使用必須繼承他.而好在蘋果公司提供了繼承NSOperation的兩個子類即NSInvocationOperation和NSBlockOperation.可見官方解釋。
The NSOperation class is an abstract class you use to encapsulate the code and data associated with a single task. Because it is abstract, youdo not use this class directly but instead subclass or use one of the system-defined subclasses (NSInvocationOperation or NSBlockOperation) to perform the actual task.
我們可以直接使用這兩個類來定義我們的操作對象,第一種是管理一個單一的封裝的任務的執行,第二種則是管理一個或多個塊中的並行執行。當然我們也可以自定義操作對象。
第五種方法,使用dispatch的分發方法,直接將需要操作的任務放進dispatch的Block塊中
dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 同步分發
dispatch_sync(quene, ^{
NSLog(@"do thing");
[NSThread sleepForTimeInterval:5];
NSThread *thread = [NSThread currentThread];
if ([thread isMainThread]) {
NSLog(@"Main Thread");
}else{
NSLog(@"Peer1 Thread");
}
NSLog(@"DONE");
});
// 異步分發
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSLog(@"do anotherthing");
[NSThread sleepForTimeInterval:5];
NSThread *thread = [NSThread currentThread];
if ([thread isMainThread]) {
NSLog(@"Main Thread");
}else{
NSLog(@"Peer2 Thread");
}
NSLog(@"DONE");
});
在線程分發的方法中,牽涉到線程優先級的問題,這裏有四種優先級
#define DISPATCH_QUEUE_PRIORITY_HIGH 2
#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0
#define DISPATCH_QUEUE_PRIORITY_LOW (-2)
#define DISPATCH_QUEUE_PRIORITY_BACKGROUND
且,他們的優先級依次降低。
最後,iOS的多線程問題是很複雜也是不容易掌握的問題,而這裏只是多線程的入門,至於程序的邏輯問題還是需要仔細分析,弄清思路。並且,多線程的使用方法需要按照項目要求使用方法。