天天看點

移動開發在路上-- IOS移動開發系列 多線程一 [轉]

類似于什麼是程序什麼是線程在這裡我就不多浪費時間了(Google一下什麼都有)!

廢話不多說先上圖,我相信大家都是喜歡看圖的人,俗話說得好,求圖求真相嗎?雖然這裡隻有屌絲一個但是真相還是會有的。。。

碼農的EQ有限,是以既沒有太多煽情的部分了

在Obj-c中線程的建立與啟動

首先說一下OC中有幾種多線程的方式

    //建立多線程對象一

NSThread *thread=[[NSThread alloc] initWithTarget:self selector:@selector(ChildThread:) object:@"子線程"];

    //開始運作多線程

start];

    //建立多線程對象二

    [NSThreaddetachNewThreadSelector:@selector(ChildThread:) toTarget:selfwithObject:@"子線程"];

    //建立多線程對象三

    [selfperformSelectorInBackground:@selector(ChildThread:) withObject:@"子線程"];

    //建立多線程對象四

    NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init];

    [threadQueue addOperationWithBlock:^(void){

                NSLog(@"---子線程---%d",i);

    }];

    //建立多線程對象五

    //建立一個線程隊列

    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];

    //同時執行的并發數

    operationQueue.maxConcurrentOperationCount = 1;

    //建立一個線程對象

    NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(ChildThread:) object:@"子線程"];

    //建立一個線程對象

    NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(ChildThread2:) object:@"子線程2"];

    //設定優先級

    operation2.queuePriority = NSOperationQueuePriorityHigh;

    [operationQueue addOperation:operation1];

    [operationQueue addOperation:operation2];

    //建立多線程對象六

    dispatch_queue_t queueq=dispatch_queue_create("test", NULL);

dispatch_async(queueq, ^{

for (int i=0; i<100; i++) {

NSLog(@"---子線程1---%d",i);

        }

        dispatch_sync(dispatch_get_main_queue(), ^{

BOOL isMain = [NSThread isMainThread];

if

NSLog(@"主線程");

            }

        });

    });

先建立一個項目

我這裡XCode版本是5.0.2

移動開發在路上-- IOS移動開發系列 多線程一 [轉]

建立一個新項目

移動開發在路上-- IOS移動開發系列 多線程一 [轉]

選擇一個空的application    建立

移動開發在路上-- IOS移動開發系列 多線程一 [轉]

下一步

移動開發在路上-- IOS移動開發系列 多線程一 [轉]

點選 建立

移動開發在路上-- IOS移動開發系列 多線程一 [轉]

到這裡我們這個項目就算建立好了。

開始 coding 

移動開發在路上-- IOS移動開發系列 多線程一 [轉]

選擇這個.m檔案

移動開發在路上-- IOS移動開發系列 多線程一 [轉]

又補充了一下子

移動開發在路上-- IOS移動開發系列 多線程一 [轉]
移動開發在路上-- IOS移動開發系列 多線程一 [轉]

到這裡先告一段落

 持續更新中...