NSThread 通過 NSRunLoop 完成單線程循環

Test.m

創建獨立的 thread:

+ (void)testThreadMain {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"test"];
        
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [runLoop run];
    }
}

// 獨立線程
+ (NSThread *)testThread {
    static NSThread *testThread = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        testThread = [[NSThread alloc] initWithTarget:self selector:@selector(testThreadMain) object:nil];
        [testThread start];
    });
    
    return testThread;
}

線程跳轉:

- (void)log {
    NSLog(@"current thread: %@", [NSThread currentThread]);
}

// 線程切換,在 main thread 中調用這個方法,切換至 testThread
- (void)test {
    [self performSelector:@selector(log) onThread:[[self class] testThread] withObject:nil waitUntilDone:NO];
}

main.m

循環調用:

#import <Foundation/Foundation.h>
#import "Test.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        for (int i = 0; i < 100; i++) {
            [[[Test alloc] init] test];
        }
        
        [NSThread sleepForTimeInterval:100];
    }
    return 0;
}

結果

打印日志:

...
2016-03-25 15:22:24.270 RunLoopTest[2436:217874] current thread: <NSThread: 0x100200310>{number = 2, name = test}
2016-03-25 15:22:24.271 RunLoopTest[2436:217874] current thread: <NSThread: 0x100200310>{number = 2, name = test}
2016-03-25 15:22:24.271 RunLoopTest[2436:217874] current thread: <NSThread: 0x100200310>{number = 2, name = test}
...

參考

深入理解RunLoop

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • runtime 和 runloop 作為一個程序員進階是必須的,也是非常重要的, 在面試過程中是經常會被問到的, ...
    made_China閱讀 1,232評論 0 7
  • runtime 和 runloop 作為一個程序員進階是必須的,也是非常重要的, 在面試過程中是經常會被問到的, ...
    SOI閱讀 21,862評論 3 63
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,778評論 18 399
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • 昨天下班臨走的時候,瞄了一眼小伙伴的屏幕,看他還在搗鼓圖像裁剪方面的東西,淡淡的問了句,又卡住了么?他說,嗯,...
    旅行著的魔法師閱讀 310評論 0 0