runloop 使用实践

#import “ViewController.h”
#import “XMGThread.h”

@interface ViewController ()
/** 线程对象 */
@property (nonatomic, strong) XMGThread *thread;
@end

@implementation ViewController

#pragma mark - 系统的方法
 /** 初始化线程 */

  • (void)viewDidLoad {
        [super viewDidLoad];
        
        self.thread = [[XMGThread alloc] initWithTarget:self selector:@selector(execute) object:nil];
        [self.thread start];
    }

/** 触摸屏幕 开始运行在子线程的方法 */

  • (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        [self performSelector:@selector(test2) onThread:self.thread withObject:nil waitUntilDone:NO];
    }

#pragma mark - 计时器(虽然runloop 添加的事件是计时器但是也可以接受 soucre的事件)
/** RunLoop 子线程计时器(运行循环处在睡眠状态 一直等着接受到timer 要处理的事件 / runloop 可以处理的事件(事件))  */

  • (void)execute
    {
        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
        
        [[NSRunLoop currentRunLoop] run];
    }

/** RunLoop 子线程计时器(运行循环处在睡眠状态 一直等着接受到timer 要处理的事件 / runloop 可以处理的事件(事件))  */

  • (void)execute
    {
       NSTimer * timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];

[[NSRunLoop currentRunLoop] run];
}

#pragma mark - 常驻线程(虽然runloop 添加的事件是soucre但是也可以接受计时器的事件)
/** RunLoop 常驻线程(线程不死 运行循环处在睡眠状态 一直等着接受到source(事件)) / runloop 可以处理的事件 */

  • (void)execute
    {
        NSLog(@"----------run----%@", [NSThread currentThread]);
        
        while (1) {
            [[NSRunLoop currentRunLoop] run];
            
            NSLog(@"--------2222");
        }
        
        NSLog(@"---------");
    }

/** RunLoop 常驻线程(线程不死 运行循环处在睡眠状态 一直等着接受到source(事件)) / runloop 可以处理的事件 */

  • (void)execute
    {
        NSLog(@"----------run----%@", [NSThread currentThread]);
        
        [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];

NSLog(@"---------");
}

#pragma mark - 计时器出发的事件

  • (void)test
    {
        NSLog(@"----------test----%@", [NSThread currentThread]);
    }

  • (void)test2
    {
        NSLog(@"****test2%@", [NSThread currentThread]);
        
    }

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值