Day.05.03 NSThread 完善线程入口方法

ViewController.m

#import "ViewController.h"

@interface ViewController ()
{
    NSThread *thread;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //创建线程
    thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadAction) object:nil];
    
    //设置名字
    thread.name = @"hehe";
    
    //启动线程
    [thread start];
    
   
    
}

//线程的入口方法
/*完善线程入口方法的三点
 1.创建自动释放池 释放开辟的内存
 2.设置runloop
 3.停止runloop,终止线程
 */
-(void)threadAction
{
    //1.创建自动释放池 释放开辟的内存
    @autoreleasepool {
        
        //延时调用
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [NSThread exit];
//        });
        
        
        //使当前线程任务持续执行 两种方式
        //第一种方式while循序
//        while (1) {
//            NSLog(@"123...");
//        }
        
        //第二种:开启runloop 子线程中runloop默认是关闭的,开启runloop必须要有事件源
        
        //创建timer定时器
        NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timer) userInfo:nil repeats:YES];
        
        //将timer添加到runloop中
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        
        //2.开启runloop 使用run的方式 无法停止runloop
//        [[NSRunLoop currentRunLoop] run];
        
        //开启runloop 运行到某个时间点停止runloop 并且带有运行模式
//        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:5]];
        
        //开启runloop 运行到某个时间点停止
//        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];
        
        //3.终止runloop的方式
//        [[[NSThread currentThread] threadDictionary] setValue:@(NO) forKey:@"isExit"];
        //获取线程字典属性  目的:记录当前前程是否退出的状态
        NSMutableDictionary *threadDictionary =[[NSThread currentThread] threadDictionary];
        
        BOOL exit = NO;
        
        [threadDictionary setValue:@(exit) forKey:@"isExit"];
        
        //while循环判断 根据线程中字典属性判断
        while (!exit) {
            
            [[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]];
            
            exit = [[threadDictionary objectForKey:@"isExit"] boolValue];
        }
    }

}

-(void)timer
{
    NSLog(@"hehe");
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //触摸屏幕时停止线程任务
    [thread.threadDictionary setValue:@(YES) forKey:@"isExit"];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

//无限循环,触摸屏幕循环停止


屏幕快照 2016-05-03 下午8.01.00.png

你可能感兴趣的:(Day.05.03 NSThread 完善线程入口方法)