iOS 多线程 - NSThread

主线程要负责UI和响应事件,不能受复杂任务拖慢,需要使用多线程。

多线程编程方法:
1.Thread :是三种方法里面相对轻量级的,但需要管理线程的生命周期、同步、加锁问题,这会导致一定的性能开销
2.NSOperation:以面向对象的方式封装了需要执行的操作,不必关心线程管理、同步等问题。NSOperation是一个抽象基类,iOS提供了两种默认实现:NSInvocationOperation和NSBlockOperation,当然也可以自定义NSOperation
3.GCD:提供了一些新特性、运行库来支持多核并行编程,在多个cpu上提升效率

一、使用步骤

1.创建线程的方法

    //实例方法
    NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(run) object:nil];
    [thread start];

    //类方法
    [NSThreaddetachNewThreadSelector:@selector(run2) toTarget:selfwithObject:nil];

    //隐式创建方法
    [selfperformSelectorInBackground:@selector(run3) withObject:nil];

二、基本属性

1.常用属性设置

    //设置线程的优先级(0,-1,1最高级)
    thread.threadPriority = 1;

    //获取当前线程
    NSThread *thread = [NSThread currentThread];

    //获取主线程
    NSThread *thread = [NSThread mainThread];

    //暂停当前线程
    [NSThreadsleepForTimeInterval:2];

    NSDate *date = [NSDatedateWithTimeInterval:2sinceDate:[NSDatedate]];
    [NSThreadsleepUntilDate:date];

2.线程间通信

1个线程传递数据给另1个线程,在1个线程中执行完特定任务后,转到另1个线程继续执行任务。

    //线程间的通信
    //在指定线程上执行操作
    [selfperformSelector:@selector(run) onThread:thread withObject:nilwaitUntilDone:YES];

    //在主线程上执行操作
    [selfperformSelectorOnMainThread:@selector(run) withObject:nilwaitUntilDone:YES];

    //在当前线程执行操作
    [selfperformSelector:@selector(run) withObject:nil];

3.线程同步/互斥锁使用格式

        //加锁方法一,使用条件锁
        [_ticketsConditionlock];
        if (_tickets >= 0 ) {
            [NSThreadsleepForTimeInterval:0.09];
            _count = 100 - _tickets;
            NSLog(@"当前票数是%d,售出%d,线程名%@",_tickets,_count,[[NSThreadcurrentThread] name]);
            _tickets--;
        } else {
            break;
        }
        [_ticketsConditionunlock];

        //加锁方法二,使用NSLock对象
        [_theLocklock];
        if (_tickets >= 0 ) {
            [NSThreadsleepForTimeInterval:0.09];
            _count = 100 - _tickets;
            NSLog(@"当前票数是%d,售出%d,线程名%@",_tickets,_count,[[NSThreadcurrentThread] name]);
            _tickets--;
        } else {
            break;
        }
        [_theLockunlock];

        //加锁方法三,使用@synchronize,只能加一把锁,多把是无效的
        @synchronized(self) {
            if (_tickets >= 0 ) {
                [NSThreadsleepForTimeInterval:0.09];
                _count = 100 - _tickets;
                NSLog(@"当前票数是%d,售出%d,线程名%@",_tickets,_count,[[NSThreadcurrentThread] name]);
                _tickets--;
            } else {
                break;
            }
        }

三、代码示例

1.创建线程、互斥锁使用、线程间通信示例

https://github.com/shileseal/SLNSThreadDemo

四、总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值