天天看点

iOS 多线程 NSthread的简单使用——iOS 编码复习(六)(多线程4)

上一篇我们简单过了一下pthread,因为那是c的API,所以一般我们不会用上,从这一篇开始,我将陆续分享我们iOS中用到的“正经”的多线程技术:NSthread、NSOperationQueue、GCD

NSThread:

NSThread的创建方法,NSthread本身只有两种方式来创建多线程:

[NSThreaddetachNewThreadSelector:@selector(buy)toTarget:selfwithObject:nil];

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

[thread1 start];

大家也注意到了,这两种方式的区别:

第一种类方法,它会立即创建一个线程并执行select方法;第二种方法则需要手动start来启动。第二种方法的好处就是可以拿到创建出来的线程,可以对该线程进行操作,比如设置优先级。

另外NSObject也提供了一个创建线程的方法:

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

 OK,那我们再去看看NSThread还有哪些经常使用的方法:

+(NSThread *)currentThread;//获得当前线程

+(void)sleepForTimeInterval:(NSTimeInterval)ti;//线程休眠

+(NSTHread*)mainThread;//主线程,即UI线程

-(BOOL)isMainThread;+(BOOL)isMainThread;//当前线程是否是主线程

-(BOOL)isExecuting;//线程是否正在运行

-(BOOL)isFinished;//线程是否已结束

-(void)cancel;//终止线程循环

-(void)start;//开启线程

OK,差不多是这样了,然后要提醒的一点是更新主线程的时候需要调用

performSelectorOnMainThread去更新主线程。

总结下:

优点:NSThread 轻量级最低,相对简单。 缺点:手动管理所有的线程活动,如生命周期、线程同步、睡眠等。

好了,到这里就差不多结束了。给大家上源码:

#pragma mark progress

- (void)progressBtnClicked

{

    //隐式创建线程

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

}

- (void)beginUploadProgressUI

{

    @autoreleasepool {

        [selfperformSelectorOnMainThread:@selector(progressMove)withObject:nilwaitUntilDone:NO];

    }

}

- (void)progressMove

{

    if (_progress.progress<1) {

        _progress.progress+=0.01;

        [NSTimerscheduledTimerWithTimeInterval:0.5target:selfselector:@selector(progressMove)userInfo:nilrepeats:NO];

    }

}

#pragma mark ticks

- (void)ticksBtnClicked

{

    _ticks = ticksNum;

    [NSThreaddetachNewThreadSelector:@selector(ticksSellBegin)toTarget:selfwithObject:nil];

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

    [thread setThreadPriority:1];

    [thread setName:@"1"];

    [thread start];

}

- (void)ticksSellBegin

{

    @autoreleasepool {

        [selfbeginUploadTicksNum];

    }

}

- (void)beginUploadTicksNum

{

    while (true) {

        [_lock lock];

        if (_ticks>0) {

            [NSThreadsleepForTimeInterval:1.0];

            [selfperformSelectorOnMainThread:@selector(updateTicksNum)withObject:nilwaitUntilDone:NO];

            _ticks--;

        }else{

            break;

        }

        [_lock unlock];

    }

}

- (void)updateTicksNum

{

    if ([[[NSThreadcurrentThread]name]isEqualToString:@"1"]) {

        _ticksLabel.backgroundColor = [UIColorgrayColor];

    }else{

        _ticksLabel.backgroundColor = [UIColorblueColor];

    }

    _ticksLabel.text = [NSStringstringWithFormat:@"共有%.2f张票",_ticks];

}

顺便提一下:[[[ NSThread   currentThread ]  name ]没有拿到那个有名字线程的名字,不知道为什么

事后代码会统一发到github上:https://github.com/FCF5646448/FCFMultithreadingDemo,敬请关注哦!!