多线程

多线程是指,将原本线性执行的任务分开成若干个子任务同步执行。

优点:防止线程“阻塞”,增强用户体验和程序效率。

缺点:代码的复杂程度会大大提高,而且对于硬件的要求也相应地提高。

常见的多线程的编码方式:NSThred;NSOperation;GCD(全称:Grand Central Dispatch)不讲.

一、NSThred的介绍

NSThred

简介:

1、创建方式

第一种:直接启动后台线程

[NSThreaddetachNewThreadSelector:@selector(task)toTarget:selfwithObject:nil];
第二种方式:手动启动线程并启动线程

NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(task)object:nil];

[thread start];

第三种方式:NSObject方法(隐式创建并启动线程)

[selfperformSelectorInBackground:@selector(task)withObject:nil];


2、控制线程状态

获取当前线程状态

+ (NSThread *)currentThread;

休眠线程

+ (void)sleepForTimeInterval:(NSTimeInterval)ti;

停止线程,不会再次开启任务

+ (void)exit;


3、线程同步:
安全隐患解决方法:互斥锁(只有一把锁)
(1) @synchronized (锁 对象 ){//代码 }
锁对象:要相同,不然没有意义。

互斥锁的优缺点:
优点:能让多条线程按顺序地执行任务。
缺点:需要耗费大量的CPU资源


4、代码:

- (void)viewDidLoad {

    [superviewDidLoad];

    NSThread *thread1 = [[NSThreadalloc]initWithTarget:selfselector:@selector(threadOneMethod)object:nil];

    NSThread *thread2 = [[NSThreadalloc]initWithTarget:selfselector:@selector(threadTwoMethod)object:nil];

    

    [thread1 start];

    [thread2 start];

}

-(void )threadOneMethod{

    @synchronized(@"nn"){

        for (int i=0; i<2; i++) {

            NSLog(@"mm");

           //循环一次休眠5秒

            [NSThreadsleepForTimeInterval:5];

        }

    }

    NSLog(@"thread1 end");

}

-(void )threadTwoMethod{

    @synchronized(@"nn"){

        for (int i=0; i<3; i++) {

            NSLog(@"dd");

            sleep(1);

        }

    }

    NSLog(@"thread2 end");

}

结果:



二、NSOperation的介绍

1、配合使用NSOperation和NSOperationQueue也能实现多线程编程。
NSOperation和NSOperationQueue实现多线程的具体步骤:
(1)先将需要执行的操作封装到一个NSOperation对象中
(2)然后将 NSOperation对象添加到NSOperationQueue中
(3)系统会自动将NSOperationQueue中的NSOperation取出来
(4)将取出的NSOperation封装的操作放到一条新的线程中执行
2、NSOperation的子类
NSOperation是一个抽象类,不具备封装操作的能力,应使用其子类。
NSOperation子类的3种使用方式:
(1) NSInvocationOperation
(2) NSBlockOperation
(3) 自定义子类继承NSOperation,实现内部相应的方法

各个子类的介绍:
1) NSInvocationOperation
创建:

- (nullableinstancetype)initWithTarget:(id)target selector:(SEL)sel object:(nullableid)arg;

代码:

NSInvocationOperation *operation=[[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(task)object:nil];


执行 执行操作后就会调用 target的sel方法(例子中的self的task 方法)。

- (void)start;

代码:
[ operation start ];


2)NSBlockOperation
创建: 

+ (instancetype)blockOperationWithBlock:(void (^)(void))block;

代码:

NSBlockOperation *operation=[NSBlockOperation blockOperationWithBlock:^{

        NSLog(@"11111“);

              }];

添加更多的操作:

- (void)addExecutionBlock:(void (^)(void))block;

代码:

[operation addExecutionBlock:^{

         NSLog(@"22222”);

    }];


3)NSOperationQueue

NSOperationQueue可以调用start方法来执行任务,默认是同步执行。

将线程对象添加到队列的方法

- (void)addOperation:(NSOperation *)op;

- (void)addOperationWithBlock:(void (^)(void))blockNS_AVAILABLE(10_6,4_0);

代码:

NSOperationQueue *operationQueue =[[NSOperationQueuealloc]init];

//获取线程对象

NSOperation *operation = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(task)object:nil];


task方法中的代码:

- (void)task {

    NSDate *beginDate = [NSDatedate];

    [NSThreadsleepForTimeInterval:3];//让当前线程休眠

    NSDate *endDate = [NSDatedate];

    NSTimeInterval duration = [endDatetimeIntervalSinceDate:beginDate];

    NSLog(@"duration = 耗时:%.2f", duration);

    //在主线程中刷新UI

    dispatch_async(dispatch_get_main_queue(), ^{

        _disPlayLabel.text =@"filish task";

        [_indicatorViewstopAnimating];

    });

    NSLog(@"我是后台线程");

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值