iOS詳解多線程(實現篇——其他方式)

在之前的章節中,我們詳細探究了多線程的相關概念、常用的實現方式(NSThread、GCD、NSOpreation),不常用的方式pThread。那麼,iOS中,還有沒有別的方式實現多線程呢?嘿嘿···你別說,還真有呢。

相關鏈接:
pThread鏈接:iOS詳解多線程(實現篇——pThread)
NSOpreation鏈接:iOS詳解多線程(實現篇——NSOperation)
GCD鏈接:iOS詳解多線程(實現篇——GCD)
NSThread鏈接:詳解多線程(實現篇——NSThread)
多線程概念篇鏈接:詳解多線程(概念篇——進程、線程以及多線程原理)

源碼鏈接:https://github.com/weiman152/Multithreading.git

多線程的實現方法

1.NSThread(OC)
2.GCD(C語言)
3.NSOperation(OC)
4.C語言的pthread(C語言)

5.其他實現多線程方法
1. 後臺執行多線程
-(void)run {
    NSLog(@"開始任務,%@",[NSThread currentThread]);
}

//後臺開啓多線程
- (IBAction)test1:(id)sender {
    [self performSelectorInBackground:@selector(run) withObject:nil];
}

運行結果:



performSelectorInBackground這個方法定義在NSObject的分類NSThreadPerformAdditions中,如下圖:



任何繼承自NSObject的類都可以使用這個方法,快速在後臺開啓線程。

2. 子線程與主線程切換
- (IBAction)test2:(id)sender {
    NSThread * t1 = [[NSThread alloc] initWithBlock:^{
        NSLog(@"哈哈哈,%@",[NSThread currentThread]);
        [self performSelector:@selector(run) onThread:[NSThread mainThread] withObject:nil waitUntilDone:NO];
    }];
    t1.name = @"線程一";
    [t1 start];
    
}

打印結果:


或者使用performSelectorOnMainThread也可以回到主線程執行任務。

NSThread * t2 = [[NSThread alloc] initWithBlock:^{
        NSLog(@"呵呵呵,%@",[NSThread currentThread]);
        [self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:NO];
    }];
    t2.name = @"線程二";
    [t2 start];
}
3. 在指定子線程執行某方法
-(void)run {
    NSLog(@"開始任務,%@",[NSThread currentThread]);
}

- (IBAction)test2:(id)sender {
    NSThread * t1 = [[NSThread alloc] initWithBlock:^{
        NSLog(@"哈哈哈,%@",[NSThread currentThread]);
        [[NSRunLoop currentRunLoop] run];
    }];
    t1.name = @"線程一";
    [t1 start];
    [self performSelector:@selector(run) onThread:t1 withObject:nil waitUntilDone:NO];
}

打印結果:


上述案例中,我們創建了一個子線程叫做線程一,我們想指定線程一中執行我們的方法run,又不想把方法寫在子線程裏面,這個時候就可以使用 [self performSelector:@selector(run) onThread:t1 withObject:nil waitUntilDone:NO];這個方法了。

本節內容對多線程的實現進行一個小小的補充,主要是performSelector的一些方法,有的時候還是很有用的。只是使用performSelector的時候要注意,此方法在編譯的時候並不會檢查方法的有效性,可能會造成一些崩潰問題,要做檢查才安全喲。

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