NSThread 和锁机制

NSThread(OC线程库)
主线程:一个iOS程序运行后,默认会开启1条线程,称为“主线程”或“UI线程”
主线程的主要作用
显示\刷新UI界面
处理UI事件(比如点击事件、滚动事件、拖拽事件等)
主线程的使用注意:别将比较耗时的操作放到主线程中。
耗时操作会卡住主线程,严重影响UI的流畅度,给用户一种“卡”的坏体验
#import "ViewController.h"

/**
 *      1.学习
        2.上厕所
 
 
 */
@interface ViewController ()

{
    NSLock *_lock;
}
@end

@implementation ViewController


-(IBAction)work:(id)sender
{
    [self doWorking];
}

-(IBAction)wc:(id)sender
{
    //[self doWC];
    //[self createTHread];
    [self createTHreads];
}

#pragma mark -NSThread 多个线程
-(void)createTHreads
{
    //创建3个线程
    
    for (int i = 0; i < 3; i++) {
        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(doWorking) object:nil];
        thread.name = @"thread";
        thread.name = [NSString stringWithFormat:@"thread%d",i];
        //设计优先级
        thread.threadPriority = i+1;
        
        [thread start];
        NSLog(@"%@",thread);
    }
    
}

#pragma mark -NSTHread 单个线程-
-(void)createTHread
{
    //返回的是一个单例
    //创建
    NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(doWorking) object:nil];
    thread1.name = @"thread1";
    //使用 必须调用才能使用
    
    [thread1 start];
    NSLog(@"%@",thread1);
    [thread1 cancel];
    
    
    
    //方法二
    //自动执行
    [NSThread detachNewThreadSelector:@selector(doWorking) toTarget:self withObject:nil];
    
    //退出
    [NSThread exit];
    
    NSLog(@"%@",[NSThread currentThread]);
    
    
}

#pragma mark -创建任务-
/**
 *  学习
 */

-(void)doWorking{
    int i = 0;
    while (i++<10) {
        //判断主线程
        NSLog(@"isMainThread:%d",[NSThread isMainThread]);
        NSThread *thread = [NSThread currentThread];
        [NSThread sleepForTimeInterval:1.0];
        NSLog(@"%@学习了%d秒",thread.name,i);
    }
    NSLog(@"完成学习任务,收获颇丰");
}

/**
 *  上厕所任务
 */
-(void)doWC{
    //创建锁
    if (_lock == nil) {
        _lock = [[NSLock alloc]init];
    }
    //上锁
    [_lock lock];
    
    int i = 0;
    while (i++<10) {
        NSThread *thread = [NSThread currentThread];
        [NSThread sleepForTimeInterval:1.0];
        NSLog(@"%@上%d秒厕所",thread.name,i);
    }
    [_lock unlock];
    NSLog(@"完成WC");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"current:%@",[NSThread currentThread]);
    NSLog(@"isMulti %d\n\n\n",[NSThread isMultiThreaded]);
    
    // Do any additional setup after loading the view, typically from a nib.
}

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

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值