常驻线程的创建

阅读: 评论:0

常驻线程的创建

常驻线程的创建

  主线程不死是因为主线程里面有一个RunLoop,RunLoop里面有一个do while死循环,保证了程序的不退出

  那么如果我们有一个需求,需要一直在后台进行某个耗时操作,比如检查联网状态,比如扫描用户的某些行为等等.

这时候肯定要在子线程进行,如果能保证一个子线程的不死,就能避免频繁的创建与销毁线程.

  方法:

  模仿主线程不死的操作

1.创建并强引用线程

2.往该线程里添加RunLoop

3.往RunLoop里面添加事务(source,timer,observer),保证RunLoop不退出

4.RunLoop run

这样我们就可以随时调用该线程处理一些任务了,代码如下

#import "ViewController.h"

#import "GQThread.h"

@interface ViewController ()


@property (nonatomic,strong)GQThread * thread; // 重写了dealloc方法,查看线程是够销毁

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

   self.thread = [[GQThreadalloc] initWithTarget:selfselector:@selector(threadBegin1)object:nil];

   self.thread.name =@"不死线程";

    [self.threadstart];



}

// threadBegin123都可以让线程不死

- (void)threadBegin1 {

 @autoreleasepool{ //必须的,下面两个方法也应该加上,处理一些autorelease对象

    [[NSRunLoop currentRunLoop] addPort:[NSPortport] forMode:NSDefaultRunLoopMode];

    [[NSRunLoopcurrentRunLoop] run];

    NSLog(@"threadBegin");//主句代码不会执行了,因为[[NSRunLoopcurrentRunLoop] run]一直在跑圈,在RunLoop内部会不断去查看该线程有没有任务要处理,若有,就让它处理一下


}


}

- (void)threadBegin2{

   while (1) {

        [[NSRunLoopcurrentRunLoop] run];

    }

}

- (void)threadBegin3{

    [NSTimerscheduledTimerWithTimeInterval:2.0target:selfselector:@selector(test)userInfo:nilrepeats:YES];

    

    [[NSRunLoopcurrentRunLoop] run];

    

}

// 自定义的一些任务给该线程执行

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [selfperformSelector:@selector(test)onThread:self.threadwithObject:nilwaitUntilDone:NO];

}

- (void)test

{

    NSLog(@"***********test2*******%@", [NSThreadcurrentThread]);

    

   // NSLog(@"%@", [NSRunLoop currentRunLoop]);

}






本文发布于:2024-02-01 14:28:40,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170676892137254.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:线程
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23