多线程:线程的状态

来源:互联网 发布:上海美知教育学院 编辑:程序博客网 时间:2024/04/30 08:06
////  ViewController.m//  04-线程状态////  Created by gzxzmac on 16/1/28.//  Copyright © 2016年 gzxzmac. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {    [self threadDemo];    // 不要在主线程调用退出方法,如果主线程调用了这个方法,程序就会死掉//        [NSThread exit];    NSLog(@"%@",[NSThread currentThread]);}- (void)threadDemo {    // 一创建就来到就绪状态//    [NSThread detachNewThreadSelector:<#(nonnull SEL)#> toTarget:<#(nonnull id)#> withObject:<#(nullable id)#>]    // 新建    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(demo) object:nil];    // 就绪状态    [thread start];    // 先休眠再取消    [NSThread sleepForTimeInterval:2.5f];    // 调用取消方法,只是对线程作一个取消的标记    [thread cancel];// 修改 cancelled 属性值 YES    NSLog(@"end");}- (void)demo {    // 判断线程是否是取消状态,在关键节点判断状态是否已经是取消    // 关键节点:耗时操作代码后面    NSThread *thread = [NSThread currentThread];    NSLog(@"睡一会");    [NSThread sleepForTimeInterval:2.6f];    if (thread.isCancelled)    {        NSLog(@"取消线程");        // 取消线程        return;    }    for (int i = 0; i < 20; ++i) {        if (thread.isCancelled) {            NSLog(@"取消线程1");            // 取消线程            return;        }        if (i == 10) {            NSLog(@"再睡一会");            [NSThread sleepForTimeInterval:2.f];            if (thread.isCancelled) {                NSLog(@"取消线程2");                // 取消线程                return;            }        }        if (i == 15) {            CGMutablePathRef path = CGPathCreateMutable();            CGPathRelease(path);            // 退出线程,要在退出线程之前,释放内存(资源),因为调用exit 方法之后,后面所有的代码都不会再去执行            NSLog(@"线程结束");            [NSThread exit];        }        NSLog(@"%@ %d",[NSThread currentThread],i);    }}@end
0 0
原创粉丝点击