多线程:线程的状态

//
//  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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值