美文网首页
iOS之创建一个常驻线程

iOS之创建一个常驻线程

作者: 13d8cd576232 | 来源:发表于2019-04-29 10:39 被阅读0次

    常驻线程有什么用呢?
    让一个一直存在的子线程,等待其他线程发来消息,处理其他事件。

    注意 :不要使用GCD的global队列创建常驻线程
    原因:global全局队列,整个工程共用的队列,队列里的所有线程都会放进一个线程池中,当线程池满了的时候,就会进入等待状态,后面加进来的block就不会创建新的线程执行了 等待前面的任务执行完成,才会继续执行。如果线程池中的线程长时间不结束,后续堆积的任务会越来越多

    @interface LongThreadDemoController ()
    @property (nonatomic, strong) NSThread *thread;
     
    @end
     
    @implementation LongThreadDemoController
     
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor whiteColor];
        self.title = @"常驻线程Demo";
         
    }
     
    - (void)threadRunloopPoint:(id)__unused object{
        NSLog(@"%@",NSStringFromSelector(_cmd));
        @autoreleasepool {
            [[NSThread currentThread] setName:@"changzhuThread"];
            NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
            //// 这里主要是监听某个 port,目的是让这个 Thread 不会回收
            [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
            [runLoop run];
        }
    }
     
     
    - (NSThread *)thread{
         
        if(!_thread){
            _thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRunloopPoint:) object:nil];
            [_thread start];
        }
        return _thread;
         
    }
     
     
     
    - (void)test{
         
        NSLog(@"%s",__func__);
    }
     
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
         
         
        [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO modes:@[NSDefaultRunLoopMode]];
         
    }
    

    个人博客地址:https://youyou0909.github.io

    相关文章

      网友评论

          本文标题:iOS之创建一个常驻线程

          本文链接:https://www.haomeiwen.com/subject/ynejmftx.html