iOS-常驻线程之线程循环调用(两个线程循环交替调用)

前言

关于线程常驻,就是当你创建一个线程以后,你希望他一直存在,但是往往当我们创建的线程执行完成以后就会停止,不能再次利用;那么我们想再次利用该线程继续工作呢?这个时候就需要我们吧该现场添加到RunLoop。

接着就是线程循环调用了,移动开发交流群(365152048)群里面的一个小伙伴有一个需求,那就是:A线程打印1结束以后B线程打印2,B线程打印结束以后再打印A线程,以此循环进行。

线程常驻

创建一个线程,然后添加到RunLoop中,代码如下:

@interface ViewController ()

@property (nonatomic, strong) NSThread *thread;//创建一个常驻线程

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)threadRunloopPoint:(id)__unused object{
    @autoreleasepool {
        [[NSThread currentThread] setName:@"ZFJThread"];
        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;
    
}

线程循环调用

#pragma mark - 开始执行
- (IBAction)onStart:(UIButton *)sender {
    [self blockOperation];
}

- (void)blockOperation{
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [self text_One_Completed:^() {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [self text_Two_Completed:^() {
        dispatch_group_leave(group);
    }];
    
    __weak typeof(self) weakSelf = self;
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [weakSelf blockOperation];
    });
    
}

- (void)text_One_Completed:(void(^)(void))completed{
    
    [self performSelector:@selector(text_One) onThread:self.thread withObject:nil waitUntilDone:NO modes:@[NSDefaultRunLoopMode]];
    
    if(completed){
        completed();
    }
}

- (void)text_Two_Completed:(void(^)(void))completed{
    
    [self performSelector:@selector(text_Two) onThread:self.thread withObject:nil waitUntilDone:NO modes:@[NSDefaultRunLoopMode]];
    
    if(completed){
        completed();
    }
}

- (void)text_One{
    
    NSLog(@"----打印线程1----");
}

- (void)text_Two{
    
    NSLog(@"====打印线程2====");
}

打印结果

iOS-常驻线程之线程循环调用(两个线程循环交替调用)_第1张图片

DEMO下载

点击下载

https://download.csdn.net/download/u014220518/10452328

结束语

欢迎各位大神补充!

欢迎大家加移动开发技术交流群,在这里大家可以一起讨论学习,这里有大佬,也有小菜鸟,没事还能斗斗图装装逼,如果需要换工作的还能相互推荐,期待大家的加入!

iOS-常驻线程之线程循环调用(两个线程循环交替调用)_第2张图片

你可能感兴趣的:(iOS开发)