ios線程篇:多線程的幾種創建方式


<span style="font-size:14px;color:#cc0000;"><strong>- (void)viewDidLoad {
    
    // 創建方式一
    NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [thread start];
    
    // 創建方式二 直接開闢並且執行
    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
    
    // 創建方式三
    [self performSelectorInBackground:@selector(run) withObject:nil];
    
    // 創建方式四
    NSOperationQueue* operation = [[NSOperationQueue alloc] init];
    operation.maxConcurrentOperationCount = 1;//指定池子的併發數
    
    // 任務A
    NSInvocationOperation* invation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
    // 任務B
    NSInvocationOperation* invation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
    //設置線程優先級
    invation.queuePriority = NSOperationQueuePriorityHigh;
    //將任務添加到池子裏面,可以給池子添加多個任務,並且指定它的併發數
    [operation addOperation:invation];
    [operation addOperation:invation1];
    
    // 第五種方式
    NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
    [operationQueue addOperationWithBlock:^{
        //這個block語句塊在子線程中執行
        NSLog(@"START");
    }];
    
    // 第六種方式
    // 調用主線程,用於子線程和主線程的交互,最後面的那個done參數如果爲yes就是等這個方法執行完了在執行
    [self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
    
    // 第六種方式
    //--------------GCD----------支持多核,高效率的多線程技術
    dispatch_queue_t queue = dispatch_queue_create("name", NULL);
    dispatch_async(queue, ^{
        NSLog(@"創建一個異步子線程");
        // 執行點什麼
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSLog(@"回到主線程 %@",[NSThread currentThread]);
            
        });
    });
    
    [super viewDidLoad];

}

- (void)run
{
    NSLog(@"多線程運行!");
}</strong></span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章