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<UITouch *> *)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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容