iOS开发之NSTread

一、NSThread基本概念

      NSThread是基于线程使用,轻量级的多线程编程方法(相对GCD和NSOperation),一个NSThread对象代表一个线程,需要手动管理线程的生命周期,处理线程同步等问题。

二、NSThread常用方法

 //实例化对象
    NSThread *objectThread = [[NSThread alloc]initWithTarget:self selector:@selector(thread) object:nil];

    objectThread.threadPriority = 1.0;
    objectThread.name = @"线程一";//名字
    //人工启动
    [objectThread start];
    //优先级
    [objectThread setQualityOfService:NSQualityOfServiceUserInitiated];
//    NSQualityOfServiceUserInteractive:最高优先级,用于用户交互事件
//    NSQualityOfServiceUserInitiated:次高优先级,用于用户需要马上执行的事件
//    NSQualityOfServiceDefault:默认优先级,主线程和没有设置优先级的线程都默认为这个优先级
//    NSQualityOfServiceUtility:普通优先级,用于普通任务
//    NSQualityOfServiceBackground:最低优先级,用于不重要的任务
    //取消
    [objectThread cancel];



    //类方法创建,静态方法
    [NSThread detachNewThreadSelector:@selector(thread) toTarget:self withObject:nil];
    //暂停
    [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
    [NSThread sleepForTimeInterval:1.0];
    //退出
    [NSThread exit];

三、线程之间的通信

// 1、指定当前线程执行操作
[self performSelector:@selector(run)];
[self performSelector:@selector(run) withObject:nil];
[self performSelector:@selector(run) withObject:nil afterDelay:3.0f];

-----------------------------分割线------------------------------------------

// 2、指定在主线程执行操作(如更新UI)
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];

-----------------------------分割线------------------------------------------

// 3、指定在其他线程操作(主线程->新线程)

// 这里指定为某个线程newThread
[self performSelector:@selector(run) onThread:newThread withObject:nil waitUntilDone:YES]; 

// 这里指定为后台线程
[self performSelectorInBackground:@selector(run) withObject:nil];

四、线程同步

多线程不可避免的会带来不同线程并发执行时争夺共享资源的问题(如内存,数据源等),这会造成数据的不一致(脏数据),甚至严重的引起死锁。

线程同步是指是指在一定的时间内只允许某一个线程访问某个资源,这就像是GCD里的栅栏(dispatch_barrier)或者信号量(dispatch_semphore)一样。

目前iOS实现线程加锁有NSLock和@synchronized两种方式

举例说明:

- (void)viewDidLoad {
    [super viewDidLoad];
ticketCount
= 20; NSThread *beijing = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil]; beijing.name = @"北京"; [beijing start]; NSThread *shenzhen = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil]; shenzhen.name = @"深圳"; [shenzhen start]; } -(void)saleTicket { while (1) { @synchronized (self) {//如果不加这句,可能出现数据错误 if (ticketCount>0) { ticketCount --; NSLog(@"剩余票数:%ld 窗口:%@",ticketCount,[NSThread currentThread].name); [NSThread sleepForTimeInterval:0.2]; }else{ break; } } } }

猜你喜欢

转载自www.cnblogs.com/laolitou-ping/p/12785210.html