NSThread

#import "ViewController.h"
/**
 *  一个NSThread对象就代表一条线程
 创建 启动线程
 // 创建
 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
 // 启动
 [thread start];
 
 */

// 调用优先级
//threadPriority

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)download:(NSString *)url {
    
    for (int i = 1; i <=100; i++) {
        if (i == 49) {
            [NSThread exit];
        }
    }
    // 拿到主线程
    NSLog(@"%@",[NSThread mainThread]);
    
    NSLog(@"%@",url);
    
    NSLog(@"%@",[NSThread currentThread]);
    // 两种睡法
    // 睡眠五秒钟
    [NSThread sleepForTimeInterval:3];
    // 3秒后的时间
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3];
    [NSThread sleepUntilDate:date];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    [self createThread2];
    
}

// 创建线程方式3
- (void)createThread3 {
    //    [self performSelector:@selector(download:) withObject:@"http://url.jpg"];
    //    [self download:@"http://url.jpg"];
    
    [self performSelectorInBackground:@selector(download:) withObject:@"http://url.jpg"];
}


/**
 *  线程3线程2 无法对线程进行详细设置
 */


// 创建线程方式2
- (void)createThread2 {
    // 从当前线程分离出一条新的线程
    [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];
}

// 创建线程方式1
- (void)creatThread1 {
    // 创建线程
    NSThread *thread  = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:nil];
    // 线程一开启就会放入‘可调度线程池’
    
    // sleep - > blocked 阻塞状态
    // 如果线程睡着了,达不到运行的状态,没有运行的能力,
    //    就会从可调度线程池中移除,但是不会被销毁
    // dead
    // 如果线程任务执行完毕,异常强制退出 就是 dead
    
    // 线程的名字
    thread.name = @"下载线程";
    [thread isMainThread];
    // 启动线程 调用download方法
    [thread start];
    // 判断当前方法是否在主线程中
    [NSThread isMainThread];
}

// 线  程 的 状 态
// 新建 - 就绪 - 开始执行 - 睡眠 - 死亡

/**
 *  控制线程状态
 
 启动线程
 start - 就绪状态-》运行状态  当线程任务执行完毕,自动进入死亡状态
 
 阻塞线程、暂停线程
 + (void)sleepUntilData:(NSData*)data;
 + (void)sleepForTimeInterval:(NSTimeInterval)ti;
 // 进入阻塞状态
 
 强制停止线程
 + (void)exit;
 // 进入死亡状态
 一旦进入死亡状态,不能再次开启任务
 
 */


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值