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,234评论 0 7
  • runtime 和 runloop 作为一个程序员进阶是必须的,也是非常重要的, 在面试过程中是经常会被问到的, ...
    SOI阅读 21,863评论 3 63
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,785评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 昨天下班临走的时候,瞄了一眼小伙伴的屏幕,看他还在捣鼓图像裁剪方面的东西,淡淡的问了句,又卡住了么?他说,嗯,...
    旅行着的魔法师阅读 311评论 0 0